Search code examples
laravelauthenticationmodellaravel-8laravel-authentication

Stop Update the update_by field of user table while Login in Laravel application


I have the following code inside my User model.

public static function boot()
    {
        parent::boot();
        static::creating(function ($model) {
            if ($user = Auth::user()) {
                $model->created_by = $user->id;
                $model->modified_by = $user->id;
            }
        });
        static::updating(function ($model) {
            if ($user = Auth::user()) {
                $model->modified_by = $user->id;
            }
        });
    }

On login, as the remember_token is updated in the user table, the updated_by is also updated. is there any way to stop updating on special occasions like login ??


Solution

  • In the updating event you can check, if the current value of remember_token is same as old one (with getOriginal method). And only then update also modified_by.

    static::updating(function ($model) {
        if ($user = Auth::user()) {
            if ($model->remember_token == $model->getOriginal('remember_token')) {
                $model->modified_by = $user->id;
            }
        }
    });