Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

alexteie's avatar

Laravel allow one session per user

Is there an easy way to do this?

0 likes
9 replies
LaryAI's avatar
Level 58

Certainly! To allow only one session per user in Laravel, you can use the database session driver and create a middleware that checks if the user has an existing session. If they do, you can log out any other sessions that the user has. Here's how you can do it:

  1. Make sure you are using the database session driver by setting the SESSION_DRIVER in your .env file:
SESSION_DRIVER=database
  1. Run the following Artisan command to create the sessions table:
php artisan session:table
  1. Run the migrations:
php artisan migrate
  1. Create a new middleware:
php artisan make:middleware SingleSessionMiddleware
  1. Open the newly created middleware file located in app/Http/Middleware/SingleSessionMiddleware.php and add the following code:
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;

class SingleSessionMiddleware
{
    public function handle($request, Closure $next)
    {
        if (Auth::check()) {
            $currentSessionId = Auth::user()->session_id;
            if ($currentSessionId != Session::getId()) {
                Auth::logout();
                return redirect('/login')->withErrors(['Your account is logged in from another device.']);
            }
        }

        return $next($request);
    }
}
  1. Now, you need to update the user's session ID each time they log in. You can do this in the authenticated method of your LoginController:
protected function authenticated(Request $request, $user)
{
    $user->session_id = Session::getId();
    $user->save();
}
  1. Finally, register the middleware in your app/Http/Kernel.php file. Add it to the $middlewareGroups array under web:
protected $middlewareGroups = [
    'web' => [
        // ...
        \App\Http\Middleware\SingleSessionMiddleware::class,
    ],
    // ...
];

Now, when a user logs in, their session ID is stored in the database. The SingleSessionMiddleware checks if the current session ID matches the one in the database. If it doesn't, it logs out the user, ensuring that only one session per user is active at any given time.

Remember to add proper error handling and user feedback to ensure a good user experience.

alexteie's avatar

then thr Auth::user()->seesion_id is empty/null but i use an custom model

alexteie's avatar

@martinbean Is there an howto because when i use this it wont work? see code here i use?

routes.php:

Route::group(['prefix' => 'admin', 'middleware' => ['web', 'auth.session', 'auth:nameguard']], function() { // some Routes }

logincontroller:

protected function authenticated(Request $request, $user): void
{
	Auth::guard('nameguard')->logoutOtherDevices($request->password));
    $user->session_id = Session::getId();
    $user->save();
}

but still all browsers are logged in? when i do incognito etc?

alexteie's avatar

Because i have admin accounts and front user account ;)

Snapey's avatar

Did you note the requirements?

Before getting started, you should make sure that the Illuminate\Session\Middleware\AuthenticateSession middleware is included on the routes that should receive session authentication. Typically, you should place this middleware on a route group definition so that it can be applied to the majority of your application's routes. By default, the AuthenticateSession middleware may be attached to a route using the auth.session route middleware alias as defined in your application's HTTP kernel:

alexteie's avatar

yes i did this is my kernel.php

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \Illuminate\Session\Middleware\AuthenticateSession::class,
    ],

Please or to participate in this conversation.