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

Robarelli's avatar

Allow only one session per user?

I am trying to implement a way for there to be only one current session per logged in user. So if device A is logged into User A and then device B logs into User A, device A will get logged out. I have a working implementation but was hoping to see if there is a more "laravel-ish" way to handle it, or if there is a way I don't have to store a session hash in the user table?


// user schema
Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('username');
            $table->string('email')->unique();
            $table->string('password', 60);
            $table->string('user_hash')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });

/*
 * User logs in and then swaps out the session
 */
class AuthController extends Controller {
 
    use AuthenticatesAndRegistersUsers;

    public function authenticated(Request $request, User $user)
    {
        $user->swap();
 
        return redirect()->intended($this->redirectPath());
    }
}
 
/*
 * Swapping implementation in User model
 */
class User extends Model implements AuthenticatableContract {
 
  use Authenticatable;
 
  public function swap()
  {
    $hash = bcrypt(auth()->user()->getKey().microtime());
 
    \Session::put('userhash', $hash);
 
    $this->user_hash = $hash;
    $this->save();
  }
}
 
/*
 * Global middleware to check for correct user hash and kick all old users
 */
class CheckUserSession
{
    public function handle($request, Closure $next)
    {
        $userhash   = \Session::get('userhash');
        $sessionId = \Session::getId();
 
        if (!auth()->guest() && auth()->user()->user_hash != $userhash) {
            \Session::getHandler()->destroy($sessionId);
            return redirect()->intended($request->getUri());
        }
 
        return $next($request);
    }
}
0 likes
2 replies
gildniy's avatar

Yeah, by missing the logout of user A, you created a loop request. Here is a simple fix. And I suggest to redirect to the desired route even after A is logged out.

class CheckUserSession
{
    public function handle($request, Closure $next)
    {
        $userhash   = \Session::get('userhash');
        $sessionId = \Session::getId();
 
        if (!auth()->guest() && auth()->user()->user_hash != $userhash) {
            \Session::getHandler()->destroy($sessionId);
            \Auth::logout();
            return redirect()->refresh();
        }
 
        return $next($request);
    }
}
3 likes

Please or to participate in this conversation.