Brian Cho Brian Cho - 1 month ago 18
PHP Question

Laravel with two different lifetime sessions

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.

Answer

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

Comments