Auto Logout Inactive Users After A Period Of Time In Laravel.


In this tutorial, I will teach you session timeout and user automatic logged out.if we use this middleware in route groups, it will be run on every request under route group.

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.

In this step, we have to create a middleware file because of Middleware acts as a bridge between a request and a response. It is a type of filtering mechanism. This tutorial explains the middleware mechanism in Laravel.

Step 1: Create Middleware file.

So, Open your terminal and put the below code.

php artisan make:middleware Sessiontimeout

In this step, we have to find app/Http/Middleware and create a new file name Sessiontimeout.php & put the below code.


namespace App\Http\Middleware;

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

class Sessiontimeout {
    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){
            $cookie = cookie('intend', $isLoggedIn ? url()->current() : 'dashboard');
        $isLoggedIn ? $this->session->put('lastActivityTime', time()) : $this->session->forget('lastActivityTime');
        return $next($request);

Step 2: Changes in Kernal file.

In this step, we have to find app/Http and open a file name Kernel.php & put the below code.

protected $middleware = [
protected $middlewareGroups = [
        'web' => [
protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,

Now open your browser put the below URL:

Here the Output:

Login Screen:

Dashboard Screen:

After Period Of Time, Click anywhere in the admin panel, You are going to login page because your session timing is out.

I hope it will help you………………

About Dhaval Shah

My name is Dhaval Shah. I'm a Laravel developer. I live in India and I love to write tutorials and tips that can help other developers. I am a big fan of PHP, Java-script, JQuery, Laravel, WordPress, and Bootstrap.
Follow me on Github / Linkedin


  1. this line is wrong ‘App\Http\Middleware\SessionDataCheckMiddleware’ it should be ‘App\Http\Middleware\Sessiontimeout’

Leave a Reply

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

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!