Laravel with two different lifetime sessions

2019-08-01 15:15发布

I'm trying to implement 'remember me' login using laravel framework. When user checks 'remember me' box, laravel keeps session data for a month. If user unchecked it, I want to keep session until user closes the browser.

I know how to control session when 'remember me' is checked. I configured sessions in config/session.php like below:

'lifetime' => 43200,
'expire_on_close' => false,

And I'm using sessions with global session helper

session(['accessToken' => SOME_ACCESS_TOKEN]);
Session::flush();

and so on.

But I don't know how to work when user logging in with 'remember me' unchecked. I tried to find a way to control the configuration

'expire_on_close' => true,

on the fly, based on user input, but failed. Please tell me how I could keep two different session lifetime configuration within one laravel framework. Or if I'm trying 'remember me' feature in wrong way, please guide me.

Basically, like I stated above, I'd like to keep session in a month with 'remember me', and keep session only until browser closing without 'remember me'.

Thanks.

1条回答
Fickle 薄情
2楼-- · 2019-08-01 15:48

In order to get remember me functionality you shouldn't work with session configuration. Instead, you should use the functionality already built into Laravel.

When you authenticate user with Auth::attempt(), you can pass a boolean value as the second argument. Set it to true, if user checked remember me checkbox. Set it to false otherwise.

This way, when checkbox is checked, user will be remembered till they manually log out of application. Otherwise, they'll be remembered till they close the browser or session expires.

You can find some more informaton here: https://laravel.com/docs/5.3/authentication#remembering-users

查看更多
登录 后发表回答