5

I'm having an issue with deleting cookies in Laravel 5.6. I've tried various different things based on this, this, this and this question, but none of them work;

1.

return response()
    ->redirectToRoute('home')
    ->withCookie(Cookie::forget('code'))
    ->withCookie(Cookie::forget('email'));

2.

Cookie::queue(Cookie::forget('code'));
Cookie::queue(Cookie::forget('email'));

return redirect('/');

3.

Cookie::queue('code', null, -1);
Cookie::queue('email', null, -1);

return redirect('/');

4.

return redirect('/')
    ->withCookie(cookie('code', '', -1))
    ->withCookie(cookie('email', '', -1));

5.

return response()
    ->redirectToRoute('home')
    ->withCookie(cookie('code', '', -1))
    ->withCookie(cookie('email', '', -1));

3, 4 and 5 don't even change the value of the cookie, the original value still remains in the cookies. I don't know what other methods I could try, so any help would be appreciated.

Cookies are generally added like this in Laravel:

return response()
    ->redirectToRoute($this->handleRedirect($result))
    ->cookie('code', $request->code, $this->duration, null, $this->domain)
    ->cookie('email', $request->email, $this->duration, null, $this->domain);
6
  • Do you have the \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class middleware enabled on your route?
    – Elie Faës
    Commented May 14, 2018 at 9:12
  • It's enabled in the $middlewareGroups array, this means it's used on all web routes by default, right?
    – Alex
    Commented May 14, 2018 at 9:16
  • for the web routes yes. You can check if it's ok with php artisan route:list
    – Elie Faës
    Commented May 14, 2018 at 9:51
  • Yeah the web middelware group is enabled on all routes, so that's not the problem.
    – Alex
    Commented May 14, 2018 at 9:56
  • How these cookies were added in the first place? By Laravel? JS? Are you able to add another one?
    – Elie Faës
    Commented May 14, 2018 at 10:01

2 Answers 2

3

Ended up switching to sessions instead of cookies as this was easier to work with according to someone I asked. I now use Session::flush() and Session::forget('key') to remove the necessary data.

2

I remember that I had some issues with laravel cookies, and finally I decided to set cookies manually with PHP's native function,

to set a new cookie use this code :

setcookie('index', 'value', time() + $secondsToRemember, '/');

and for deleting them use this code :

setcookie('index', 'Expired', time() - 100000, '/');

this is the easiest way of handling cookies.

and after that code you can return back or redirect user or do something else

you can read this page for more detailed explanation : https://www.w3schools.com/php/php_cookies.asp

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.