Search code examples
phplaraveleloquentmigration

Larevel - Save last user request timestamp


I want to save the datetime of last interaction of a user with the application inside the user table.

I'm using Laravel 8.

I added a column in users table (last_interaction):

Schema::create('users', function(Blueprint $table)
        {
            $table->engine = 'InnoDB';
            $table->integer('id', true);
            $table->string('firstname');
            $table->string('lastname');
            $table->string('username', 192);
            $table->string('email', 192);
            $table->string('password');
            $table->string('avatar')->nullable();
            $table->string('phone', 192);
            $table->integer('role_id');
            $table->boolean('statut')->default(1);
            $table->datetime('last_interaction'); //The column where to save the datetime of last interaction
            $table->timestamps(6);
            $table->softDeletes();
        });

Is it possible to update the users table with each request done! or should i do it on login only (for Optimisations) ?


Solution

  • You can make new middleware with this command php artisan make:middleware LastInteraction

    App\Http\Middleware\LastInteraction.php:

    public function handle(Request $request, Closure $next)
    {
        if (Auth::check()) {
            $user = Auth::user();
            $user->last_interacted = Carbon::now();
            $user->save();
        }
    
        return $next($request);
    }
    

    This will set a field of last_interacted to the current time given this field exists in your migration. If it doesn't exist create one.

    App\Http\Kernel.php

    protected $middleware = [
    
        (...)
    
        \App\Http\Middleware\LastInteraction::class,
    ];
    

    This will register the middleware to be applied globally to each route.