Laravel logout user’s on session expires. 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
Follow the following steps and 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, we have to find app/Http 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,
],
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.