Laravel 8 Automatic logout inactive users after a period of time

Sometimes we want to make automatic logged out inactive users after a few minutes. This feature is useful in payment terminal application.

In this article, I will show you how you can logged out inactive users after a specific period of time in Laravel 8 application.

We will add middleware to check user status. This middleware will check every request that user was active or inactive.

Step 1: Create Middleware file

To create a middleware, run the following command into Terminal.

php artisan make:middleware AutoLogout

This will create a new middleware class at app/Http/Middleware/AutoLogout.php file. Open middleware file and add the below code into handle() method.

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Session\Store;

class AutoLogout
{
    protected $session;
    protected $timeout = 1200;

    public function __construct(Store $session)
    {
        $this->session = $session;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $is_logged_in = $request->path() != 'dashboard/logout';

        if(!session('last_active')) {
            $this->session->put('last_active', time());
        } elseif(time() - $this->session->get('last_active') > $this->timeout) {
            
            $this->session->forget('last_active');
            
            $cookie = cookie('intend', $is_logged_in ? url()->current() : 'dashboard');
            
            auth()->logout();
        }

        $is_logged_in ? $this->session->put('last_active', time()) : $this->session->forget('last_active');
        
        return $next($request);
    }
}

Step 2: Register middleware in Kernel.php file

Now we also need to register middleware at app/Http/Kernel.php file. So open Kernel.php file and middleware into $middleware array.

/**
 * The application's global HTTP middleware stack.
 *
 * These middleware are run during every request to your application.
 *
 * @var array
 */
protected $middleware = [
    \App\Http\Middleware\TrustProxies::class,
    \Fruitcake\Cors\HandleCors::class,
    \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    \App\Http\Middleware\AutoLogout::class
];

Run the Laravel server using below command into Terminal.

php artisan serve

Now login to user, The user will automatically logged out after a specific period of time.

I hope you liked the article. Thanks for giving time in reading articles.