【问题标题】:Catch model event in middleware - Laravel 5.4在中间件中捕获模型事件 - Laravel 5.4
【发布时间】:2017-03-23 18:37:30
【问题描述】:

我正在尝试记录应用程序的每个请求的数据。如果用户保存特定模型的数据,我会尝试将原始数据保存在与activity_logs 表关联的revisions 表中。

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

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;
    }

【问题讨论】:

  • 你能贴出调用save方法的代码吗?想知道是否在您在会话中设置活动日志 id 值的中间件之前调用模型保存
  • 我现在已经更新了我的问题,以包括将 activity_log_id 放置在会话中的中间件代码
  • 这个handle()方法在哪个中间件上?
  • handle方法在Tracker路由中间件上。
  • 代码中的模型保存在哪里?是商店功能吗?如果是,您可以看到在为活动日志 id 设置会话变量之前调用了 save 方法

标签: laravel laravel-5.4


【解决方案1】:

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

如果你移动

            $next_request = $next($request);

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-12
    • 2021-06-08
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    • 2014-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多