Josh Bolton
Josh Bolton

Reputation: 768

Catch model event in middleware - Laravel 5.4

I am trying to log data on each request of the application. If a user saves data for a particular model, i am trying to save the original data in a revisions table which is associated to an activity_logs table.

I have tried using model events to capture the data as follow:

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

However, It seems that the model event is being fired before the middleware is instantiated so although the revision is being saved, it is being saved in the previous GET request instead of the new PUT request.

An example of the activity_logs is below: Example of activity logs Any help is much appreciated.

EDIT: Update to include tracking middleware code:

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

Upvotes: 2

Views: 790

Answers (1)

Kim Ward
Kim Ward

Reputation: 142

You are running the controller before you are creating the new activitylog record.

If you move

            $next_request = $next($request);

to after you've created the log record then the new log record will be created before the models save method is executed.

Upvotes: 2

Related Questions