Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 343
Pankaj Avatar asked Aug 05 '16 20:08

Pankaj


2 Answers

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.

like image 68
Steve Bauman Avatar answered Oct 19 '22 03:10

Steve Bauman


$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();      
        });
    }
like image 43
KmasterYC Avatar answered Oct 19 '22 04:10

KmasterYC