Cookie is not deleting using Cookie::forget() after logout
Hi all,
I'm creating a cookie to display modal after the user's first log in using javascript. If the user logout from the site. I'm deleting the cookie using Cookie::forget() function. When I log in again, the cookie is there. It is not deleting on user logout. Here is my code:
public function logout(Request $request)
{
\Cookie::forget('first_time');
$this->guard()->logout();
$request->session()->invalidate();
return $this->loggedOut($request) ?: redirect('/');
}
js
$(document).ready(function () {
setTimeout(function () {
var cookie = $.cookie('first_time');
if (!cookie) {
$('#edit-interest').modal('show');
$.cookie('first_time', 1);
}
},3000);
});
@manelgavalda I've used your code. it storing cookie first_name without value. and created date showing Thursday, November 21, 2019 at 4:12:09 PM and expires showing Thursday, November 21, 2019 at 4:12:09 PM.
When I logged in again, the same cookie showing created Thursday, November 21, 2019 at 3:35:09 PM and expires When the browsing session ends.
@manelgavalda I've tried but same result as I mentioned.
I'm creating cookie after user login. When they redirect to their home page after login then, I check if the cookie exists using my js. if not a modal will be triggered and a cookie will set.
The browser won't remove a cookie from its storage, it will keep its info there even when expired. The difference is that it won't send an expired cookie on a request header.
I don't know any method of the server instructing the browser on how it should manage its own storage.
What the server can do is say: Hey this one is expired! How the client, in this case the browser, will proceed is not up to the server to know about.
On login you can send a new Cookie with the same name with a new expiration date.
EDIT
On alternative that came to my mind: on your login screen you can add a JavaScript to check for expired cookies and remove them locally on page load. This way there won't be any expired cookies before sending the login request.
Maybe cookies that are not marked http only are not deleted by server action.
Also, this only detects first login on this device. Are you happy that if the user logs in from somewhere else, they see the first use modal again?
I would keep it server side. If the User created_at and updated_at are the same value then this is first login. Touch the User model then return the view to the client with the modal included.