Pankaj
Pankaj

Reputation: 10105

Trying to logout particular user from Admin System: Laravel 5.2.37

I am writing the following code to logout particular user from Admin System.

I have session table. I am following this link : https://laravel.com/docs/5.2/session

$User = $this->Get($obj);
$UserSession = SessionModel::where('user_id', $obj->UserID)->first();
if($UserSession != null) {
    $UserSession->user_id = null;
    $UserSession->payload = null;
    $UserSession->save();
}

Is it a correct approach to do so?

Upvotes: 9

Views: 477

Answers (3)

Steve Bauman
Steve Bauman

Reputation: 8678

You can really clean this up in one line of code:

$deleted = SessionModel::whereUserId($obj->UserID)->delete();

// Returns the number of deleted sessions.
return $deleted;

Deleting all session records that belong to a user will log the user out of all sessions they have.

For example, if a user is logged in on your application on their phone and computer, they will be logged out on both devices.

Upvotes: 6

KmasterYC
KmasterYC

Reputation: 2354

$User = $this->Get($obj);
$UserSession = SessionModel::where('user_id', $obj->UserID)->first();
if($UserSession != null) {
    $UserSession->user_id = null;
    $UserSession->payload = null;
    $UserSession->save();
}

You must noticed that is user can have more session records if user logs in with many different browser
=> Solution: get all rows with given user_id in sessions table and delete them. Use useful Collection method

    $User = $this->Get($obj);
    // Get Collection Object
    $UserSessions = SessionModel::where('user_id', $obj->UserID)->get();
    if($UserSession != null) {
        // Use each method on Collection Object
        $UserSessions->each(function($UserSession){
              $UserSession->delete();      
        });
    }

Upvotes: 3

sha-1
sha-1

Reputation: 2093

You might consider that the user_id in your Session table should be nullable and have a default null value, since users that are not logged in have no user id. Then your migration might have this line.

$table->integer('user_id')->unsigned()->nullable()->default(null);

Then deleting the row of a specific user in this table would delete that users session.

Upvotes: -1

Related Questions