Enter your keyword

Laravel Session Timeout (Auto Logout)

Laravel Session Timeout (Auto Logout)

In this tutorial, we are going to implement session time for our Laravel Project. We will auto logout a user if they have been inactive for a specified time and redirect to the login page.

Add last_seen_at to the User model.

Am assuming, you already setup authentication. If not so, refer here.

Run the following artisan command to create the migrate, and update it as follows.

php artisan make:migration add_last_seen_to_users_table --table=users

Update database

php artisan migrate:refresh

Create session timeout middleware

This middleware will check it if a user is already logged in, but has been inactive longer than the specified period; there by invalidate their session and auto log them out.

php artisan make:middleware SessionTimeout

You can get the complete SessionTimeout middleware file here.

Register middleware to web guard

Set user last seen on login

Override the authenticated() in the LoginController method and update the user last seen time.

Set session lifetime

You may set a preferred inactivity period in you environment variables

That’s it, hope it saved you day.