Laravel Session Timeout (Auto Logout)
In this tutorial, we are going to implement session time for our Laravel Project. We will auto logout a user if they have been inactive for a specified time and redirect to the login page.
Add last_seen_at
to the User model.
Am assuming, you already setup authentication. If not so, refer here.
Run the following artisan command to create the migrate, and update it as follows.
php artisan make:migration add_last_seen_to_users_table --table=users
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class AddLastSeenToUsersTable extends Migration { public function up() { Schema::table('users', function (Blueprint $table) { $table->timestamp('last_seen_at')->nullable(); }); } public function down() { Schema::table('users', function (Blueprint $table) { $table->dropColumn('last_seen_at'); }); } } |
Update database
php artisan migrate:refresh
Create session timeout middleware
This middleware will check it if a user is already logged in, but has been inactive longer than the specified period; there by invalidate their session and auto log them out.
php artisan make:middleware SessionTimeout
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 30 31 32 |
class SessionTimeout { public function handle($request, Closure $next) { // If user is not logged in... if (!Auth::check()) { return $next($request); } $user = Auth::guard()->user(); $now = Carbon::now(); $last_seen = Carbon::parse($user->last_seen_at); $absence = $now->diffInMinutes($last_seen); // If user has been inactivity longer than the allowed inactivity period if ($absence > config('session.lifetime')) { Auth::guard()->logout(); $request->session()->invalidate(); return $next($request); } $user->last_seen_at = $now->format('Y-m-d H:i:s'); $user->save(); return $next($request); } } |
You can get the complete SessionTimeout middleware file here.
Register middleware to web guard
1 2 3 4 5 6 7 8 9 |
class Kernel extends HttpKernel { // ... protected $middlewareGroups = [ 'web' => [ // ... \App\Http\Middleware\SessionTimeout::class, ], } |
Set user last seen on login
Override the authenticated()
in the LoginController
method and update the user last seen time.
1 2 3 4 5 6 7 8 9 |
class LoginController extends Controller { // ... protected function authenticated(Request $request, $user) { $user->last_seen_at = Carbon::now()->format('Y-m-d H:i:s'); $user->save(); } } |
Set session lifetime
You may set a preferred inactivity period in you environment variables
1 2 |
# Session lifetime in minutes SESSION_LIFETIME=10 |
That’s it, hope it saved you day.