redirect user on session expire in laravel

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

We can achieve same by many methods but most effective and easy method is using middleware.

While using middleware method to logout user on session expire, we need to specify user session expiry (when user expire), you can set any amount of time for this. In this method, practically we store time when user log in and then each time user request to access specific URLs then it check current time with last request time. If difference between both times greater then expiry time then it will force user to logout and redirect to login page.

Now let's assume your application perfectly working with authentication process. let's get started

  • Step 1: Create Middleware
  • Step 2: Register the Middleware in Kernel file
  • Step 3: Logout Logic in Middleware
  • Step 4: Running Our Application

Create Middleware

So first of all, Open your terminal or command prompt, navigate to root directory of your project and run the following command:

php artisan make:middleware php artisan make:middleware SessionCheck

This command will create a middleware name php artisan make:middleware SessionCheck.php at app/Http/Middleware

Register the Middleware in Kernel file

In this step, we need to register our newly created middleware into kernel file. So, open app/Http directory and open file name Kernel.php and make following changes:


namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
     * The application's global HTTP middleware stack.
     * These middleware are run during every request to your application.
     * @var array
    protected $middleware = [
        // \App\Http\Middleware\TrustHosts::class,

     * The application's route middleware groups.
     * @var array
    protected $middlewareGroups = [
        'web' => [
            // \Illuminate\Session\Middleware\AuthenticateSession::class,

        'api' => [
            // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,

     * The application's route middleware.
     * These middleware may be assigned to groups or used individually.
     * @var array
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,

You can register middleware into kernel as per you requirements like global, route specific or custom.

Logout Logic in Middleware

At last, we have to create our logic for check session is expired or not and if session is expired then we need to logout user. For that make following changes into SessionCheck.php file :


namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Session\Store;
use Auth;
use Session;
class SessionCheck
    protected $session;
    protected $timeout = 1000; //Session Expire time in seconds
    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);

In this example code, when user navigate to other page or refresh current page then this logic check last activity time with current time and if last activity time is not in session then it will store it. If difference between last activity time and current time is less then expiry time then it will force user to logout otherwise it doesn't effect on user.

Here, you can set $timeout(expiry time) as per your requirements. Please note expiry time is in seconds.

Running Our Application

start server using below command :

php artisan serve

Now open your browser put the below URL:


Share your thoughts

Ask anything about this examples