在中间件中捕获模型事件 - Laravel 5.4

Catch model event in middleware - Laravel 5.4

我正在尝试记录应用程序的每个请求的数据。如果用户为特定模型保存数据,我试图将原始数据保存在与 activity_logs table.[=19= 关联的 revisions table 中]

我尝试使用模型事件来捕获数据,如下所示:

class BaseModel extends Model
{
    public static function boot()
    {
        parent::boot();

        static::saving(function($model){
            $revision = new Revision;
            $revision->table_name = $model->getTable();
            $revision->row_id = $model->id;
            $revision->data = json_encode($model->getDirty());
            $revision->save();

            $log = ActivityLog::find(Session::pull('activity_log_id'));
            $log->revision_id = $revision->id;
            $log->save();
        });
    }
}

但是,模型事件似乎是在中间件实例化之前被触发的,因此尽管正在保存修订,但它是保存在先前的 GET 请求中而不是新的 PUT 请求。

activity_logs 的示例如下: 非常感谢任何帮助。

编辑:更新以包含跟踪中间件代码:

public function handle($request, Closure $next)
    {
        // Handle the next response and check tracking cookie
        if($request->hasCookie('session_tracking')) {
            $cookie_id    = Cookie::get('session_tracking');
            $next_request = $next($request);
        } else {
            $cookie_id    = Uuid::generate()->string;
            $next_request = $next($request)->withCookie(cookie('session_tracking', $cookie_id));
        }

        // Get user agent data
        $agent = new Agent();
        $exception = $next_request->exception;

        // Store associated log data
        $path    = $this->storePaths($request);
        $browser = $this->storeBrowser($agent);
        $os      = $this->storeOS($agent);
        $device  = $this->storeDevice($agent);
        $error   = $this->storeError($exception);

        // Store the collated log
        $activitylog = $this->storeLog($path, $browser, $os, $device, $agent, $request, $cookie_id, $error);

        Session::put('activity_log_id', $activitylog->id);

        return $next_request;
    }

在创建新的活动日志记录之前,您是 运行 控制者。

如果你移动

            $next_request = $next($request);

在您创建日志记录之后,将在执行模型保存方法之前创建新的日志记录。