Laravel - Cookie
Laravel - Cookie
Section titled “Laravel - Cookie”HTTP cookies are small pieces of data that a server sends to the user’s web browser. The browser may store it and send it back with subsequent requests to the same server. Laravel provides an easy way to create, retrieve, and manage cookies. By default, all cookies generated by Laravel are encrypted and signed, so they cannot be modified or read by the client.
Creating / Setting Cookies
Section titled “Creating / Setting Cookies”There are a few ways to set cookies in Laravel:
1. Attaching to a Response:
Section titled “1. Attaching to a Response:”You can attach a cookie to an outgoing Illuminate\Http\Response instance using the cookie method. This method accepts the name, value, duration in minutes, path, domain, secure, and httpOnly arguments.
use Illuminate\Http\Response;
// In a controller methodreturn response('Hello World')->cookie( 'user_preference', 'dark_mode', 60 // 60 minutes);
// With more options:return response('Another Response')->cookie( 'session_id', 'xyz123', 120, '/', null, true, true // name, value, minutes, path, domain, secure, httpOnly);2. Using the Cookie Facade (Queueing Cookies):
Section titled “2. Using the Cookie Facade (Queueing Cookies):”If you want to set a cookie before the response is created, you can use the Cookie facade’s queue method. These cookies will be automatically attached to the outgoing response.
use Illuminate\Support\Facades\Cookie;
// In a controller method or serviceCookie::queue('username', 'john_doe', 60 * 24); // Cookie for 1 day
// You can also queue a Cookie instance for more control:$cookie = cookie('theme', 'light', 120, null, null, false, true); // httpOnly = trueCookie::queue($cookie);Setting Cookies ‘Forever’:
Section titled “Setting Cookies ‘Forever’:”To create a long-lived cookie (effectively ‘forever’, typically 5 years), you can use the forever method:
Cookie::queue(Cookie::forever('api_key', 'secret-api-value'));
// Or when attaching to a response:return response('API Key Set')->cookie(Cookie::forever('api_key', 'secret-api-value'));Retrieving Cookies
Section titled “Retrieving Cookies”Once a cookie has been set, you can retrieve its value from the incoming Illuminate\Http\Request instance using the cookie method, or by using the Cookie facade’s get method.
1. From the Request Object:
Section titled “1. From the Request Object:”// In a controller methoduse Illuminate\Http\Request;
public function showUserSettings(Request $request){ $userPreference = $request->cookie('user_preference'); // Returns 'dark_mode' or null $username = $request->cookie('username', 'default_guest'); // With a default value
// return view('settings', ['preference' => $userPreference, 'username' => $username]); return "Preference: {$userPreference}, Username: {$username}";}2. Using the Cookie Facade:
Section titled “2. Using the Cookie Facade:”use Illuminate\Support\Facades\Cookie;
$theme = Cookie::get('theme'); // Returns 'light' or null$apiKey = Cookie::get('api_key', null); // Default value can be specifiedDeleting Cookies
Section titled “Deleting Cookies”To delete a cookie, you can queue a cookie with the same name but an empty value and an expired timestamp. Laravel provides a forget method for this.
1. Using Cookie::queue() with Cookie::forget():
Section titled “1. Using Cookie::queue() with Cookie::forget():”Cookie::queue(Cookie::forget('user_preference'));2. Attaching an Expired Cookie to a Response:
Section titled “2. Attaching an Expired Cookie to a Response:”return response('Cookie removed')->withoutCookie('username');The withoutCookie method effectively achieves the same as queuing a forgotten cookie.
Example: Implementing Cookie Operations in a Controller
Section titled “Example: Implementing Cookie Operations in a Controller”Step 1: Create a CookieDemoController.
php artisan make:controller CookieDemoControllerStep 2: Add methods to app/Http/Controllers/CookieDemoController.php.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;use Illuminate\Http\Response;use Illuminate\Support\Facades\Cookie;
class CookieDemoController extends Controller{ public function setAppCookie(Request $request): Response { $minutes = 60; // Cookie valid for 60 minutes $cookieValue = 'LaravelTutorial-' . time();
// Using Cookie::queue (cookie will be added to the response automatically) // Cookie::queue('my_app_cookie', $cookieValue, $minutes); // return response('Cookie has been set via queue!');
// Or directly attaching to response return response('Cookie has been set directly!') ->cookie('my_app_cookie', $cookieValue, $minutes); }
public function getAppCookie(Request $request): string { $value = $request->cookie('my_app_cookie'); // Or: $value = Cookie::get('my_app_cookie');
if ($value) { return 'Retrieved cookie value: ' . $value; } return 'Cookie not found or expired.'; }
public function deleteAppCookie(Request $request): Response { // Using Cookie::queue with Cookie::forget() // Cookie::queue(Cookie::forget('my_app_cookie')); // return response('Cookie queued for deletion!');
// Or directly removing from response return response('Cookie has been deleted!') ->withoutCookie('my_app_cookie'); }}Step 3: Define routes in routes/web.php.
use App\Http\Controllers\CookieDemoController;
Route::get('/cookie/set', [CookieDemoController::class, 'setAppCookie'])->name('cookie.set');Route::get('/cookie/get', [CookieDemoController::class, 'getAppCookie'])->name('cookie.get');Route::get('/cookie/delete', [CookieDemoController::class, 'deleteAppCookie'])->name('cookie.delete');Step 4: Test the cookie operations by visiting the URLs:
http://your-app.test/cookie/set: Sets the cookie. Check your browser’s developer tools (Application > Cookies) to see it.http://your-app.test/cookie/get: Retrieves and displays the cookie’s value.http://your-app.test/cookie/delete: Deletes the cookie. Refresh the get URL or check developer tools to confirm it’s gone.
Practical Application: Remembering User Preferences
Cookies are often used to store non-sensitive user preferences like:
- Theme (dark/light mode)
- Language selection
- Items in a shopping cart for guest users
- Remembering if a user has seen a welcome message or a promotional popup.
Common Learning Obstacle: Cookie Not Set Immediately
A common point of confusion is that cookies are sent to the browser with the HTTP response. This means if you set a cookie and then try to retrieve it within the same request cycle using $request->cookie(), you won’t get the newly set value. The browser needs to receive the response, store the cookie, and then send it back on a subsequent request. Cookie::queue() helps manage this as Laravel ensures queued cookies are part of the outgoing response.
Additional Resources:
Section titled “Additional Resources:”- Laravel Documentation on HTTP Cookies: https://laravel.com/docs/requests#cookies (Retrieving)
- Laravel Documentation on HTTP Responses (Attaching Cookies): https://laravel.com/docs/responses#cookies