Although there’s many ways to do this in Laravel, the simplest way is with a piece of web
middleware.
When an authenticated user visits a route in our application, we want to store the timestamp in the database for use later on. Let’s store it in a column called last_active_at
.
All you need to do is create a migration:
php artisan make:migration add_last_active_at_to_users_table --table=users
And add the following line in the up()
method:
$table->timestamp('last_active_at')->nullable();
If the user has never visited a route, it will remain NULL
in the database.
We also want to make sure this field is “fillable”, so add last_active_at
to the protected $fillable
array on your User
model.
As well as being able to update last_active_at
using User::update()
, we want to cast it to a Carbon\Carbon
instance when using it so that we can make use of time comparison methods.
#laravel