Last Updated: September 29, 2021
·
92.33K
· jpcamara

Deleting cookies in Laravel

The conventional approach to removing cookies from Laravel is to call the #forget method on the Cookie facade.

$cookie = \Cookie::forget('myCookie');

But when we do that, the cookie remains. What went wrong? Well, we need to make sure to add that cookie to the response.

return response('view')->withCookie($cookie);

Now the cookie was removed. But that's kind of annoying, and easy to forget. Plus, what if we're returning some JSON and want to use the cleaner return syntax.

\Cookie::forget('myCookie');
return ['ok' => true];

Do we have to lose the syntax just so we can remove the cookie?

\Cookie::queue

Instead of making sure I remember to add my $cookie object to the response, I instead use the #queue method to avoid it all together.

\Cookie::queue(\Cookie::forget('myCookie'));
return ['ok' => true];

The #queue method allows you to queue up the result of whatever cookie action you're working on, be it creating or deleting, and it handles adding it to the headers during a middleware process following your controller action.

Following this approach consistently means you never have to worry about whether you've added the $cookie to your response or not. Enjoy!