How to invalidate particular session in Laravel (w

2019-05-11 03:12发布

Using Laravel 5.1 & 'file' Session Driver,

I'm trying to provide facility to user to track their sessions and invalidate them anytime they wish by keeping a record of their session_id within the database. With Database, I mean, I maintain a table called user_sessions which associates user_id with their session_id (obtained by Session::getId()).

So, to invalidate Session, I tried the following code,

$sessionId = Session::getId();
Session::setId($sessionId);
Session::invalidate();

and it works perfectly fine, for the case where, where user does not uses Remember Me feature.

For the case where user uses Remember Me feature, this above code does not work, So, I additionally, tried setting remember_token field to null as specified here in this answer, but with this, all sessions of the user get destroyed including the current one.

2条回答
Evening l夕情丶
2楼-- · 2019-05-11 03:34

You can simply use

use Illuminate\Support\Facades\Session;

Session::forget('YOUR_SESSION_ID');

If you want to get the current session Id:

Session::driver()->getId();

I hope it helps

查看更多
ら.Afraid
3楼-- · 2019-05-11 03:42

Sessions are meant to be short-lived. If you want something a bit more permanent you can use some sort of a long term user settings table.

Create a table user_settings:

id (PK), user_id(FK users table), settings(BLOB?), created_at, updated_at

Add a model:

class UserSetting extends Model {
      public function user() {
            return $this->belongsTo(User::class);
      }
}

You can also associate the user with these via :

 class User extends Model {
 //...
     public function settings() {
         $this->hasMany(UserSetting::class);
     }
 }

You can then get all user sessions via:

 User::find($u)->settings();

When a user logs in regularly or automatically via a remember token a Login event is fired.

You can listen to this in your event service provider:

\Event::listen(\Illuminate\Auth\Events\Login::class, function ($event) {
       // Here you can load the last settings in the session if you want e.g. 
       session(['current_settings' => $event->user->settings()->latest()->value('id') ]); 
        // or you can just make a new entry: 
        $settings = new UserSettings();
        $event->user->settings()->save($settings);
        session(['current_settings' => $settings->id ]);
});

Note that you will have to manually persist things that need persisting instead of just putting them in the session.

查看更多
登录 后发表回答