Laravel Logout on Session Expire

Laravel Logout on Session Expire

Laravel session expired redirect to login. In this tutorial, you will learn how to logout and redirect users to the login page when session timeout or session expired.

As well as, you can schedule a task using cron job and artisan command to auto-logout when session expired/session timeout and redirect user’s.

Laravel Logout on Session Expire

Steps to logout and redirect the user if their session is expired or session timeout:

Step 1: Create Middleware file

So, Open your terminal and run the following command:

php artisan make:middleware SessionExpired

This command will create a middleware name SessionExpired.php.

Next find app/Http/Middleware/SessionExpired.php & update the following code into your middleware file:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Session\Store;
use Auth;
use Session;

class SessionExpired {
    protected $session;
    protected $timeout = 1200;
    
    public function __construct(Store $session){
        $this->session = $session;
    }
    public function handle($request, Closure $next){
        $isLoggedIn = $request->path() != 'dashboard/logout';
        if(! session('lastActivityTime'))
            $this->session->put('lastActivityTime', time());
        elseif(time() - $this->session->get('lastActivityTime') > $this->timeout){
            $this->session->forget('lastActivityTime');
            $cookie = cookie('intend', $isLoggedIn ? url()->current() : 'dashboard');
            auth()->logout();
        }
        $isLoggedIn ? $this->session->put('lastActivityTime', time()) : $this->session->forget('lastActivityTime');
        return $next($request);
    }
}

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

If you want to change anything in middleware code according to your requirement, you can do.

Step 2: Register the Middleware in Kernal file

In this step, Visit app/Http directory and open a file name Kernel.php & put the below code.

protected $middleware = [
        'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
        'Illuminate\Cookie\Middleware\EncryptCookies',
        'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
        'Illuminate\Session\Middleware\StartSession',
        'Illuminate\View\Middleware\ShareErrorsFromSession',
        'App\Http\Middleware\SessionDataCheckMiddleware'
    ];
protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \App\Http\Middleware\SessionExpired::class,

        ],
protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
    ];

Now open your browser put the below URL:

http://127.0.0.1:8000/

Conclusion

In this tutorial, you have learned how to auto-logout users after a period of time in laravel apps.

Recommended Laravel Posts

Recommended:-Laravel Try Catch

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

One reply to Laravel Logout on Session Expire

  1. Dear Devendra, I just wanted to tell you that your tutorial “Laravel Logout on Session Expire” was very helpful to me and I thank you for this because I searched everywhere to find a way to log out when there was no activity. I created the middleware and it is working fine. One thing I noted is that is that your timeout set (1200 = 20 min) must also be less that the session lifetime setting in .env (usually 120 = 2 hours) otherwise a new session is created before the Session Check and then the LastActivity time is reset to current time.

Leave a Reply

Your email address will not be published. Required fields are marked *