You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 5.6中Cookie::forget()无法删除Cookie的问题求助

Hey there, I’ve dealt with this exact cookie headache in Laravel before, so let’s get to the bottom of this. The root issue here is probably a mismatch in cookie attributes between when you set them and when you try to delete them.

Looking at how you add the cookies:

return response()
    ->redirectToRoute($this->handleRedirect($result))
    ->cookie('code', $request->code, $this->duration, null, $this->domain)
    ->cookie('email', $request->email, $this->duration, null, $this->domain);

You’re explicitly setting the domain parameter, but none of your deletion attempts include that same domain. Browsers only let you modify/delete cookies if all attributes (domain, path, secure, etc.) match exactly—so your previous methods were being ignored by the browser.

Here are the corrected versions of your methods that should work:

Method 1 (with Cookie::forget and domain)

return response()
    ->redirectToRoute('home')
    ->withCookie(Cookie::forget('code', null, $this->domain))
    ->withCookie(Cookie::forget('email', null, $this->domain));

The Cookie::forget method accepts parameters in this order: name, path, domain, secure, httpOnly. We’re passing the same domain you used when setting the cookie.

Method 2 (with Cookie::queue and domain)

Cookie::queue(Cookie::forget('code', null, $this->domain));
Cookie::queue(Cookie::forget('email', null, $this->domain));
return redirect('/');

Same idea here—attach the domain to the Cookie::forget call so the browser recognizes which cookie to delete.

Method 3/4/5 (manual expiration with matching attributes)

If you prefer the manual expiration approach, make sure to include every attribute that matches your original cookie setup:

return redirect('/')
    ->withCookie(cookie('code', '', -1, null, $this->domain))
    ->withCookie(cookie('email', '', -1, null, $this->domain));

This sets the cookie value to empty, expires it immediately (-1), and uses the same path (null defaults to /) and domain as your original cookie.

Extra Troubleshooting Tips:

  • Double-check your browser’s cookie storage (Chrome: DevTools > Application > Cookies) to confirm the exact domain of the code and email cookies. If it’s something like .yourdomain.com (with a leading dot), make sure you’re using that exact value in $this->domain.
  • If your site uses HTTPS, verify if you set the secure parameter when creating cookies. If you did, add that parameter to your deletion calls too (e.g., Cookie::forget('code', null, $this->domain, true)).
  • Ensure the path parameter matches—you used null (default /) when setting, so keep it consistent in deletion.

Once you align all the cookie attributes, the deletion should work as expected!

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:33:41