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

rwoodr's avatar

Limiting user to single session, with remember token

With a new install of Laravel 5 I'd like to be able to use the included user scaffolding, but limit the user to a single logged in session. When a user logs in on another browser/computer the previous session should be invalidated. If they never log in on another system I'd like the remember token to keep them logged in indefinitely. I've found a few hints by searching and put together something that works for the initial testing (below). Is there a better way?

First, I added a session_id column to the users table.

In AuthenticatesAndRegistersUsers.php postLogin function I replaced this:

if ($this->auth->attempt($credentials, $request->has('remember')))
{
    return redirect()->intended($this->redirectPath());
}

With this:

if ($this->auth->validate($credentials)) {
    $user = $this->auth->getLastAttempted();

    $previous_session = $user->session_id;

    if ($previous_session) {
        \Session::getHandler()->destroy($previous_session);
        $this->auth->setUser($user);
        $this->auth->logout();
    }

    $this->auth->login($user, $request->has('remember'));

    $user->session_id = \Session::getId();
    $user->save();

    return redirect()->intended($this->redirectPath());
}

And in the getLogout function I added this to the top:

$user = \App\User::find($this->auth->id());
$user->session_id = null;
$user->save();
0 likes
1 reply
emiliogrv's avatar

thanks for your code, really helped me a lot, but I realized that if you came back to the previous page User 1 and you logout, to logout the user 2 also.

so change this

$user = \App\User::find($this->auth->id()); $user->session_id = null; $user->save();

for this

if(isset(Auth::user()->session_id)){ $user = User::find($this->auth->id());
if(Auth::user()->session_id === $user->session_id){ $user->session_id = null; $user->save(); } }

sorry if confusing, use google translator

Please or to participate in this conversation.