In Laravel 5, you can get the specified cookie value in the current request through the $request->cookie()
method. If you want to delete a specific cookie, you can use the withCookie()
method on the Response
instance and set the cookie's expiration time to a time in the past. For example:
return response('Hello World')->withCookie(cookie('name', null, -1));
The above code will set the value of the cookie named name
in the response to null
, and set its expiration time to a timestamp in the past. In this way, the browser will no longer save the cookie, thus enabling deletion.
If you want to delete all cookies, you can loop through all cookies and set their expiration time to the past time.
foreach($_COOKIE as $key => $value) { setcookie($key, $value, time() - 3600, '/'); }
The above code will first traverse all cookies, and then use the setcookie()
function to set the expiration time of each cookie to the current time minus one hour, and set its path to root path. If you are using Laravel 5, you can use the Cookie
helper function it provides to achieve the same effect.
foreach($_COOKIE as $key => $value) { Cookie::queue(Cookie::forget($key)); }
Cookie::forget()
The method will create a new Cookie
instance and set its expiration time to the past time. The Cookie::queue()
method then adds the instance to the response, thus enabling the deletion.
The above is the detailed content of laravel5 delete cookies. For more information, please follow other related articles on the PHP Chinese website!