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?
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.
$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();
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With