laravel 5.1 - 没有为model :: update()函数调用特征启动

时间:2015-08-21 11:13:20

标签: laravel laravel-5.1

我在此页面上创建了如下特征app / Traits / ModelEventThrower.php

namespace App\Traits;

use Input;
use Event;
use App\Events\ActivityLog;
use Illuminate\Database\Eloquent\Model;
//use Illuminate\Support\Facades\Event;

/**
 * Class ModelEventThrower 
 * @package App\Traits
 *
 *  Automatically throw Add, Update, Delete events of Model.
 */
trait ModelEventThrower {

    /**
     * Automatically boot with Model, and register Events handler.
     */
    protected static function bootModelEventThrower()
    {

        foreach (static::getModelEvents() as $eventName) {

            static::$eventName(function (Model $model) use ($eventName) {
                try {

                    $reflect = new \ReflectionClass($model);

                    echo "here";exit;

                  } catch (\Exception $e) {
                    return true;
                }
            });
        }
    }

    /**
     * Set the default events to be recorded if the $recordEvents
     * property does not exist on the model.
     *
     * @return array
     */
    protected static function getModelEvents()
    {
        if (isset(static::$recordEvents)) {
            return static::$recordEvents;
        }

        return [
            'created',
            'updated',
            'deleted',
        ];
    }
}

我的城市模型是这样的

namespace App;

use App\Traits\ModelEventThrower;
use App\Events\ActivityLog;

use Illuminate\Database\Eloquent\Model;
use Event;

class City extends Model
{
    use ModelEventThrower;
    //protected static $recordEvents = ['updated'];
...
}

我的CitiesController是

namespace App\Http\Controllers\Admin;

use App\City;
use App\Country;
use Input;
use Validator;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class CitiesController extends Controller
{
......
    public function update(City $city,Request $request)
    {
     ......
    $city->where('id','=',$input['id'])->update($input);

不知何故,我没有看到它调用trait文件中写的函数。当我尝试创建$city->create($input);时,它会回声#34;这里"并且停止执行,但不对更新功能执行相同操作,但是我可以成功更新记录。

任何建议/帮助都将受到高度赞赏。

1 个答案:

答案 0 :(得分:1)

我与Laravel有类似的问题。通过在模型中添加构造函数来调用父boot()的{​​{1}}函数,如下所示:

Model

你可以确保引导所有特征。这解决了我。