0
我需要偵聽模型中的更新事件,但我需要對模型中不存在的一些變量進行建模。我是通過向模型添加公共變量來實現的,但是當我只對這些'假'屬性進行更改時,我無法聽到。無論如何要通過'假'屬性來建模並可以偵聽更新嗎?Laravel Eloquent在表中沒有實際變化時監聽事件
這是我的示例類。
<?php
class School extends Eloquent {
protected $table = 'schools';
protected $fillable = array('name', 'type_id', 'city');
protected $guarded = array('id');
public $set_specialties;
protected static function boot()
{
parent::boot();
static::updating(function($model)
{
$data = array(
'name' => $model->name,
'type_id' => $model->type_id,
'specialties' => $model->set_specialties,
'city_id' => $model->city_id
);
$rules = array(
'name' => 'required|min:3|max:50',
'type_id' => 'required|min:1|max:300000',
'specialties' => 'required|array',
'city_id' => 'required|min:1|max:300000'
);
$validator = Validator::make($data, $rules);
if ($validator->fails()) {
throw new ValidationException(null, null, null, $validator->messages());
} else {
return true;
}
});
static::updated(function($model)
{
if ($model->set_specialties != null)
{
$model->specialty()->sync($model->set_specialties);
}
});
}
}
這裏是我的更新方法從控制器:
public function update($id)
{
$data = Input::only('name', 'type_id', 'description', 'info_specialties', 'contacts', 'specialties', 'financing_id', 'district_id', 'city_id');
$school = School::find($id);
$school->name = $data['name'];
$school->type_id = $data['type_id'];
$school->set_specialties = $data['specialties'];
$school->city_id = $data['city_id'];
try {
$school->save();
} catch (ValidationException $errors) {
return Redirect::route('admin.schools.edit', array($id))
->withErrors($errors->getErrors())
->withInput();
}
return Redirect::route('admin.schools.edit', array($id))
->withErrors(array('mainSuccess' => 'It's updated successful!'));
}
我可以使用模型觀察者嗎? – mertindervish 2015-02-10 20:52:18
可能是更好! – GeekRiky 2015-02-11 06:31:01