Laravel Cookie:删除 Cookie
问题
在Laravel 中,如何删除一个 cookie?
回答
首先澄清一个概念,所谓删除一个 cookie,其实就是使之立即过期失效。我们可通过 Cookie 门面的 forget
方法来实现:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
class TestController extends Controller
{
public function index(Request $request)
{
$cookie = Cookie::forget('name');
return response('view')->withCookie($cookie);
}
}
首先通过 Cookie::forget
得到一个过期的 cookie 对象,然后将其附加到响应中即可。
有时我们可能会忘记将 cookie 附加至响应输出中,使得删除操作不起作用。推荐使用 Cookie
门面的 queue 方法,中间件会自动将「队列」中的 cookie 在内容输出至浏览器之前附加到响应中:
Cookie::queue(\Cookie::forget('name'));
请问如何清空所有cookie,或者同时删除多个cookie呢?
@sunny-kevin
Looking at the Laravel source code (https://github.com/laravel/framework/blob/...), there doesn't seem to be a function to delete all the cookies at once, so you only option would indeed be to loop over all the cookies and delete them one by one.
@陈伯乐 好的,谢谢