To create cookies in Laravel, use the cookie() helper or withCookie() method with parameters for name, value, duration, path, domain, secure, and httpOnly flags; 2. Retrieve cookies via $request->cookie('name') or Cookie::get('name'), noting Laravel automatically decrypts cookies set by its system; 3. Delete cookies by sending a past-expiration cookie using Cookie::forget('name') or manually setting a negative expiration time; 4. Queue cookies globally with Cookie::queue() for automatic attachment to the next response and configure encryption exceptions in the EncryptCookies middleware by adding names to the $except array; 5. Follow best practices such as avoiding sensitive data storage, setting appropriate expiration, using HTTPS, and testing with browser tools—Laravel simplifies secure cookie management with Cookie::queue() for setting, $request->cookie() for reading, and Cookie::forget() for deletion, ensuring proper state handling across requests.
Working with cookies in Laravel is straightforward thanks to its clean API and built-in support for secure, encrypted cookies by default. Laravel uses Symfony’s Symfony\Component\HttpFoundation\Cookie
class under the hood, but provides easy-to-use helpers for creating, retrieving, and deleting cookies.

Here’s how to work with cookies effectively in Laravel:
1. Creating and Sending Cookies
To send a cookie with a response, use the cookie()
helper or withCookie()
method on a response instance.

Example: Add a cookie to a response
use Illuminate\Http\Response; Route::get('/set-cookie', function () { return response('Cookie set!') ->cookie('user_name', 'JohnDoe', 60); // name, value, duration in minutes });
This sets a cookie named user_name
with value JohnDoe
that lasts for 60 minutes.
With additional options:
->cookie('user_name', 'JohnDoe', 60, '/', '.yourdomain.com', true, true)
Parameters:

name
– cookie namevalue
– cookie valueminutes
– lifetimepath
– path where cookie is availabledomain
– domain (optional)secure
– only send over HTTPShttpOnly
– not accessible via JavaScript
You can also use the Cookie
facade for more control:
use Illuminate\Support\Facades\Cookie; $response = response('Cookie set!'); $response->withCookie(cookie()->make('user_name', 'JohnDoe', 60)); return $response;
Or create encrypted cookies (Laravel encrypts cookies by default unless you use cookie()->forever()
or unencrypted()
):
// Encrypted and queued to be sent with the next response Cookie::queue('preferences', 'dark_mode', 1440); // queued for 24 hours
2. Retrieving Cookies
Use the Cookie
facade or the Request
object to read cookies.
From the request:
use Illuminate\Http\Request; Route::get('/get-cookie', function (Request $request) { $name = $request->cookie('user_name'); return $name ? "Hello, $name" : 'No cookie found'; });
Using the Cookie facade:
$name = Cookie::get('user_name');
?? Note: Laravel decrypts cookies automatically if they were set using Laravel's cookie system. But you can only retrieve cookies set by Laravel if they were encrypted.
3. Deleting Cookies
To delete a cookie, send a cookie with the same name but with a null value and a past expiration.
return response('Cookie deleted') ->withCookie(Cookie::forget('user_name'));
Using Cookie::queue()
:
Cookie::queue(Cookie::forget('user_name'));
Alternatively, manually set an expired cookie:
->cookie('user_name', '', -1) // negative time deletes it
4. Global Cookie Configuration and Queuing
Laravel allows you to queue cookies using Cookie::queue()
. This is useful when you want to set a cookie without immediately returning a response.
Cookie::queue('welcome_message', 'Thanks for visiting!', 120);
The cookie will be attached automatically to the next outgoing response.
You can also customize cookie behavior globally in config/session.php
and App\Http\Middleware\EncryptCookies
.
? By default, Laravel encrypts all cookies via the
EncryptCookies
middleware (App\Http\Middleware\EncryptCookies
). If you need to allow unencrypted cookies (e.g., for JavaScript access), add the cookie name to the$except
array:
class EncryptCookies extends BaseEncrypter { protected $except = [ 'tracking_id', // this cookie won't be encrypted ]; }
5. Best Practices and Tips
-
Use
queue()
for convenience – avoids manually attaching cookies to responses. - Avoid storing sensitive data – even though cookies are encrypted, they're still stored on the client side.
- Set appropriate expiration times – don’t keep cookies longer than necessary.
- Use HTTPS in production – especially if setting secure cookies.
- Test cookie behavior – browser dev tools help verify if cookies are set correctly (path, domain, secure flag).
Working with cookies in Laravel is simple and secure by default. Whether you're remembering user preferences, tracking sessions, or handling authentication tokens, Laravel’s cookie layer makes it easy to manage state across requests—just remember to handle encryption and expiration appropriately.
Basically, use Cookie::queue()
for setting, $request->cookie()
for reading, and Cookie::forget()
for cleanup.
The above is the detailed content of How to work with cookies in Laravel?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

ToworkeffectivelywithpivottablesinLaravel,firstaccesspivotdatausingwithPivot()orwithTimestamps(),thenupdateentrieswithupdateExistingPivot(),managerelationshipsviadetach()andsync(),andusecustompivotmodelswhenneeded.1.UsewithPivot()toincludespecificcol

Laravelprovidesacleanandflexiblewaytosendnotificationsviamultiplechannelslikeemail,SMS,in-appalerts,andpushnotifications.Youdefinenotificationchannelsinthevia()methodofanotificationclass,andimplementspecificmethodsliketoMail(),toDatabase(),ortoVonage

Dependency injection automatically handles class dependencies through service containers in Laravel without manual new objects. Its core is constructor injection and method injection, such as automatically passing in the Request instance in the controller. Laravel parses dependencies through type prompts and recursively creates the required objects. The binding interface and implementation can be used by the service provider to use the bind method, or singleton to bind a singleton. When using it, you need to ensure type prompts, avoid constructor complications, use context bindings with caution, and understand automatic parsing rules. Mastering these can improve code flexibility and maintenance.

Laravel performance optimization can improve application efficiency through four core directions. 1. Use the cache mechanism to reduce duplicate queries, store infrequently changing data through Cache::remember() and other methods to reduce database access frequency; 2. Optimize database from the model to query statements, avoid N 1 queries, specifying field queries, adding indexes, paging processing and reading and writing separation, and reduce bottlenecks; 3. Use time-consuming operations such as email sending and file exporting to queue asynchronous processing, use Supervisor to manage workers and set up retry mechanisms; 4. Use middleware and service providers reasonably to avoid complex logic and unnecessary initialization code, and delay loading of services to improve startup efficiency.

Methods to manage database state in Laravel tests include using RefreshDatabase, selective seeding of data, careful use of transactions, and manual cleaning if necessary. 1. Use RefreshDatabasetrait to automatically migrate the database structure to ensure that each test is based on a clean database; 2. Use specific seeds to fill the necessary data and generate dynamic data in combination with the model factory; 3. Use DatabaseTransactionstrait to roll back the test changes, but pay attention to its limitations; 4. Manually truncate the table or reseed the database when it cannot be automatically cleaned. These methods are flexibly selected according to the type of test and environment to ensure the reliability and efficiency of the test.

LaravelSanctum is suitable for simple, lightweight API certifications such as SPA or mobile applications, while Passport is suitable for scenarios where full OAuth2 functionality is required. 1. Sanctum provides token-based authentication, suitable for first-party clients; 2. Passport supports complex processes such as authorization codes and client credentials, suitable for third-party developers to access; 3. Sanctum installation and configuration are simpler and maintenance costs are low; 4. Passport functions are comprehensive but configuration is complex, suitable for platforms that require fine permission control. When selecting, you should determine whether the OAuth2 feature is required based on the project requirements.

Laravel simplifies database transaction processing with built-in support. 1. Use the DB::transaction() method to automatically commit or rollback operations to ensure data integrity; 2. Support nested transactions and implement them through savepoints, but it is usually recommended to use a single transaction wrapper to avoid complexity; 3. Provide manual control methods such as beginTransaction(), commit() and rollBack(), suitable for scenarios that require more flexible processing; 4. Best practices include keeping transactions short, only using them when necessary, testing failures, and recording rollback information. Rationally choosing transaction management methods can help improve application reliability and performance.

The core of handling HTTP requests and responses in Laravel is to master the acquisition of request data, response return and file upload. 1. When receiving request data, you can inject the Request instance through type prompts and use input() or magic methods to obtain fields, and combine validate() or form request classes for verification; 2. Return response supports strings, views, JSON, responses with status codes and headers and redirect operations; 3. When processing file uploads, you need to use the file() method and store() to store files. Before uploading, you should verify the file type and size, and the storage path can be saved to the database.
