In this tutorial you will learn about the Laravel Logout on Session Expire and its application with practical example.
In this Laravel Logout on Session Expire tutorial I’ll show you how to logout user’s on session expires. In this tutorial, you will learn to logout user and redirect to the login page when user session timeout or expired. In laravel you can also 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
1 |
php artisan make:middleware SessionExpired |
Step 1: Create Middleware file
This command will create a middleware name SessionExpired.php. Next find app/Http/Middleware/SessionExpired.php & update the following code into your middleware file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<?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); } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
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:
1 |
http://127.0.0.1:8000/ |