Laravel Eloquent 在 table 中实际没有变化时监听事件

Laravel Eloquent listen events when there aren't actually changes in table

我需要监听模型中的更新事件,但我需要将一些 table 中不存在的变量放入模型中。我通过向模型添加 public 变量来实现它,但是当我仅对这些 'fake' 属性进行更改时,我无法收听。有没有办法将 'fake' 属性传递给模型并可以监听更新?

这是我的例子class。

<?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!'));
}

可以创建自定义事件,here官方文档!