Cookie::forget not working laravel 5.1

2019-04-22 10:37发布

问题:

I'm trying to get Laravel 5.1 to delete my cookie, however it will not delete even though i'm returning it with my redirect.

return redirect('/voucher')->withCookie(Cookie::forget($cookie));

Have I done something wrong?

回答1:

Maybe I am wrong, but you are probably using cookie object in place of cookie name when calling Cookie::forget($cookie). Unless $cookie is a string containing cookie name, you should try something like this:

return redirect('/voucher')->withCookie(Cookie::forget('cookie_name'));


回答2:

I know this is already an old and answered question but I got here recently and if I'm correct, the cookie needs to be 'queued' for the next response.

You can do that by adding the cookie manually to the response as @Jan.J already described in his answer. But if you need to do it inline, this might also work for you:

Cookie::queue(
    Cookie::forget('cookieName')
);

The CookieJar will pass all queued cookies to the next response.



回答3:

In my case there was an array stored in the cookie, so none of provided methods has worked. Array should be deleted providing exactly pair of array:

Cookie::queue(Cookie::forget('array_name[provide_key]'));


回答4:

public function funname(CookieJar $cookie)

    session()->flush();

$cookie->queue(cookie()->forget('user_email')); $cookie->queue(cookie()->forget('user_password'));

return redirect('/');


回答5:

You can also do it this way:

redirect('/')->cookie(cookie()->forget('my_super_cookie_name))