Skip to content

Laravel5 Inactivity idle session logout

Last updated on February 17, 2018

In this post, I would like to show how to automatically log out the user after some period of inactivity. Session timeout or Session expire depends on the server configuration so in order to achieve our target we are going to write middleware in the Laravel5. Without making any changes to server configurations we will use last activity time to log out the user.

Open your config/session.php and specify the number of minutes that you wish the session to be allowed to remain idle before it expires.

'lifetime' => 10,

automatically logout user after some period of inactivity
Create a file called SessionDataCheckMiddleware.php in App\Http\Middleware location and copy past below code.

getLastUsed()))) {
            
            $request->session()->flush(); // remove all the session data
            
            Auth::logout(); // logout user
            
        }

        return $next($request);
    }

}

Now open \app\Http\Kernel.php file, add our custom “SessionDataCheckMiddleware” middleware

use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel {
     /**
     * The application's global HTTP middleware stack.
     *
     * @var array
     */
     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'
     ];
     /**
     * The application's route middleware.
     *
     * @var array
     */
     protected $routeMiddleware = [
          'auth' => 'App\Http\Middleware\Authenticate',
          'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
          'guest' => 'App\Http\Middleware\RedirectIfAuthenticated'
     ];
}

That is it.

0 0 votes
Article Rating
Subscribe
Notify of
guest

15 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments