Wednesday, August 1, 2018

Laravel Allow Single Login Only


Recently in one of my project we need functionality to allow only single session for user. So if I am logged in with one user account then I can not use it on other device. If they try to do so, it will log you out from first last session and will continue with current session.

So here is the trick I have used is to store active session id to users table and then check it with new session id on login. If both are not same then destroy the old session.

So first of all create migration and add session id column in users table.

Schema::table('users', function($table)

Now in your AuthController or LoginController add following function after user is authenticated.

$user = \Auth::user();
$currentSessionId = $request->session()->getId();
if($lastSessionId != null){
if($currentSessionId != $lastSessionId){
//destroy last session
$user->session_id = $currentSessionId;

So here it will destroy old session and create new one. Please note this is one way to achieve single login. There could be better trick, in that case please share here.lara