Home » Php » Trying to avoid Duplicate User's Session Records in Session Table: Laravel

Trying to avoid Duplicate User's Session Records in Session Table: Laravel

Posted by: admin October 29, 2017 Leave a comment

Questions:

Sample data in this table looks like below:

enter image description here

There are multiple duplicate User’s Session records present in the table.

vendor\laravel\framework\src\Illuminate\Session\DatabaseSessionHandler.php

In the above file path, we have below method

public function write($sessionId, $data)
{
    $payload = $this->getDefaultPayload($data);

    if (! $this->exists) {
        $this->read($sessionId);
    }
    if ($this->exists) {
        $this->getQuery()->where('id', $sessionId)->update($payload);
    } else {
        $payload['id'] = $sessionId;

        $this->getQuery()->insert($payload);
    }

    $this->exists = true;
}

It checks for Session ID.

Question

Can I avoid creation of duplicate User Session Records in Session Table? Is there any flag that do so in Session Config file?

Answers:

It seems to be an error in your traitement, must be like this no ? :

 if (! $this->exists) {
    $this->read($sessionId);
}else{

   if ($this->exists) {
       $this->getQuery()->where('id', $sessionId)->update($payload);
   } else {
       $payload['id'] = $sessionId;
       $this->getQuery()->insert($payload);
   }
}

Questions:
Answers:

From your question, you want only leave one user session in database, which means one user can only login from one device, example if you already logined from chrome , then if you login from firefox, your chrome login status will be removed.

To acheive this you can write a function in App\Http\Controllers\Auth\AuthController:

public function authenticated(Request $request,User $user){
    $previous_session = $user->session_id;

    if ($previous_session) {
    \Session::getHandler()->destroy($previous_session);
    }

    Auth::user()->session_id = \Session::getId();
    Auth::user()->save();
    return redirect()->intended($this->redirectPath());
}

this function will destory prvious session from database before login.
for more info you should check Trait :Illuminate\Foundation\Auth\AuthenticatesUsers