Laravel: How to log out a user after a time of inactivity.

Julio Motol
2 min readApr 6, 2020

--

Photo by Kate Stone Matheson on Unsplash

So your user has been asleep and you want to log them out of your application. But how do you do that?

You have probably seen and tried:

// Somewhere in your config\session.php"lifetime" => 120,

As we all know this can drastically affect our application (trust me, we did). If we are to set this to a lower value like 15 and a user takes the same time to fill up a very long form, they’ll get a TokenMismatchException. That ended up causing more trouble than help us.

Now what could be a better way to do this? In this article we’ll be covering just that! We’ll be implementing an Authentication Timeout for your Laravel Application!

For this we will be using Laravel Auth Timeout, a small package that does the thing for you. Start by installing the package through composer.

composer require juliomotol/laravel-auth-timeout

After that, we’ll include a Middleware in our Kernel.php.

protected $middleware = [
...
\JulioMotol\AuthTimeout\Middleware\AuthTimeoutMiddleware::class,
...
];

And your done! As simple as that. By default, your user has 15 mins of inactivity time before they are logged out. But if you want to change that, first publish the config file:

php artisan vendor:publish --provider="JulioMotol\AuthTimeout\ServiceProvider"

This will generate an auth-timeout.php inside your config directory. Then find the timeout key and set the duration in minutes.

Now you should be seeing that your users are logged out when they’ve been inactive. A quick and simple setup. If you want to dig more about the package, there are more configuration available so be sure to check out Laravel Auth Timeout.

I hope you’ll find this useful.

--

--