<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class CookieController extends Controller { public function showUserId(Request $request) { $userId = $request->cookie('user_id', 'guest'); return response()->json(['user_id' => $userId]); } }
The cookie() method on the Request object returns the cookie value if it exists. If it does not, it returns the default value provided as the second argument. Here, 'guest' is the default, so the output JSON will have 'user_id' set to 'guest'.
In Laravel, the cookie() method's third parameter is the duration in minutes. So passing 10 sets the cookie to expire in 10 minutes. Passing a string like '10m' is invalid.
<?php return response('Delete cookie')->cookie('session_id', '', -1);
To delete a cookie, Laravel sets it with an expiration time in the past. However, if the path or domain differs from the original cookie, the browser will not delete it. This is a common cause of cookie deletion failure.
<?php namespace App\Http\Middleware; use Closure; class CheckVisited { public function handle($request, Closure $next) { if (!$request->cookie('visited')) { $response = $next($request); return $response->cookie('visited', 'yes', 60); } return $next($request); } }
On the first request, the cookie 'visited' is not present, so middleware sets it with value 'yes'. The browser stores it and sends it back on the second request, so the cookie exists with value 'yes'.
Laravel automatically encrypts all cookies except those listed in the $except array of the EncryptCookies middleware. This ensures cookie data is secure by default.