Laravel Sessions and Cookies Explained
On your invoice list page, a user changes the setting to show 50 rows per page. They click an invoice, read it, and click back to the list. The page shows 10 rows again. Their choice is gone, and they have to change it every single time.
This happens because the web has no memory. Every request is a separate conversation. When the user clicks a link, your app has no idea that this is the same person who asked for 50 rows a moment ago.
Sessions and cookies are the two tools that solve this problem. In this lesson you will learn how both work, how to store and read data with each, and how to choose between them.
HTTP Has No Memory
HTTP, the protocol behind every website, is stateless. Each request arrives alone, and the server forgets it as soon as the response is sent. Look at what your app sees:
Request 1: GET /invoices?per_page=50 --> shows 50 rows Request 2: GET /invoices/1001 --> shows one invoice Request 3: GET /invoices --> who is this? shows 10 rows
To remember anything, the app needs a way to recognize the same visitor across requests, and a place to keep the information. That is exactly what a session provides.
What Is a Session?
A session is a small storage area on the server that belongs to one visitor. When someone first visits your app, Laravel creates a session for them and gives it a random ID. The ID is sent to the browser inside a cookie. On every later request the browser sends the cookie back, and Laravel uses the ID to find the right session.
First visit:
Browser --> GET /invoices
<-- response + cookie: session ID = abc123
Next visits:
Browser --> GET /invoices/1001 (cookie: abc123)
Laravel finds session abc123 on the server
and loads the data stored in it
The important detail is that the data itself stays on your server. The browser holds only the ID. This is why a session is a safe place for private information, such as the logged-in user.
Where Sessions Are Stored
The place where session data is kept is called the session driver. The settings live in config/session.php, and the most important ones are read from your .env file. You will study the .env file in the Environment Configuration lesson, so for now only the main values matter:
SESSION_DRIVER=database SESSION_LIFETIME=120
In a fresh Laravel project, the default driver is database, which keeps sessions in a table called sessions. The SESSION_LIFETIME value is the number of minutes a session can stay idle before it expires, and its default is 120 minutes. The sessions table is created by the migrations that come with a new project, so the command you ran after installing Laravel has already prepared it.
Laravel supports several other drivers, and you can choose one by changing SESSION_DRIVER:
filestores sessions as files instorage/framework/sessionsdatabasestores sessions in a table, and works well when your app runs on more than one serverredisstores sessions in Redis, which is very fast, and you will meet it in the Caching with Redis lessoncookiestores everything inside an encrypted cookie in the browserarraykeeps data only for the current request, and is used in tests
For learning and for most small projects, the default is a good choice.
Working with Sessions
You can use the session in two ways. The first is the session() helper, which works anywhere. The second is the session object on the request, which you can reach in a controller through $request->session(). Both do the same job.
Storing and Reading Data
To save a value, pass an array to the helper, or use put(). To read it, use session() with the key, and an optional default value:
session(['per_page' => 50]);
$request->session()->put('per_page', 50);
$perPage = session('per_page');
$perPage = session('per_page', 10); // 10 if nothing is stored
Now we can fix the problem from the start of the lesson. In InvoiceController, remember the user’s choice, and use it on later visits:
public function index(Request $request)
{
if ($request->filled('per_page')) {
session(['invoice_per_page' => $request->integer('per_page')]);
}
return [
'per_page' => session('invoice_per_page', 10),
'invoices' => $this->invoiceService->all(),
];
}
Open /invoices?per_page=50, then open /invoices without the query string. The value stays at 50, because it came from the session. The filled() and integer() methods are the ones you learned in the Request Object lesson. We use filled() so that an empty ?per_page= does not overwrite the saved value.
Checking, Removing and Clearing
The session object has a small set of methods that you will use again and again:
session()->has('per_page'); // true if the key exists and is not null
session()->exists('per_page'); // true if the key exists, even when null
session()->forget('per_page'); // remove one key
session()->pull('per_page'); // read the value and remove it in one step
session()->flush(); // remove everything from the session
session()->all(); // get everything as an array
The difference between has() and exists() is the same idea as has() and filled() on the request. A key can be stored with the value null, and has() treats that as missing.
Working with Lists
When you want to keep a list, for example the last few invoices a user opened, use push(). It adds a value to an array stored in the session:
public function show(int $invoice)
{
session()->push('recent_invoices', $invoice);
// ...
}
$recent = session('recent_invoices', []); // [1001, 1003, 1001]
There is also session()->increment('visits') for counters. Notice that we store only the invoice number, and not the whole invoice. Keep sessions small and store identifiers. Fetch the full data from the database when you need it.
Flash Data Is Session Data
In the last lesson you used ->with('status', 'Invoice created') to show a one-time message after a redirect. That message is stored in the session too. The only difference is that Laravel removes it after the next request. You can also create it yourself with session()->flash('status', 'Invoice created'), which does the same job as with().
Keeping Sessions Safe
Laravel manages the session ID for you, but two actions are your responsibility when you build login features. When a user logs in, the session ID should be changed with regenerate(), and when they log out the session should be destroyed with invalidate(). These protect against an attacker who knows an old session ID. The Authentication chapter will show you where Laravel already does this for you.
$request->session()->regenerate(); // new ID after login $request->session()->invalidate(); // destroy the session on logout
Also keep in mind that session data belongs to one browser only. A user who opens your site on their phone and on their laptop has two separate sessions.
What Is a Cookie?
A cookie is a small piece of text that your app asks the browser to store. The browser then sends it back automatically with every request to your site. The browser keeps cookies even after it is closed, until they expire.
Response --> Set-Cookie: theme=dark; Max-Age=2592000 Every later request: Browser --> Cookie: theme=dark
You already know one cookie, the one that carries the session ID. Cookies are good for small preferences that do not need to be secret, such as a theme, a language or a banner the user has closed. Browsers limit a cookie to about 4 KB, and it travels with every request, so keep cookies tiny.
Reading and Writing Cookies
Reading a Cookie
Read a cookie from the request with cookie(). You can pass a default value, just like with input:
$theme = $request->cookie('theme', 'light');
Writing a Cookie
A cookie is written by attaching it to the response. The lifetime is given in minutes, not seconds:
return response('Theme saved')
->cookie('theme', 'dark', 60 * 24 * 30); // 30 days
return redirect()
->route('invoices.index')
->cookie('theme', 'dark', 60 * 24 * 30);
If it is not convenient to touch the response, for example deep inside a service, use the Cookie facade. Its queue() method keeps the cookie ready and attaches it to the next response automatically:
use Illuminate\Support\Facades\Cookie;
Cookie::queue('theme', 'dark', 60 * 24 * 30);
Deleting a Cookie
To remove a cookie, tell the browser to forget it:
return redirect()
->route('invoices.index')
->withoutCookie('theme');
Cookie::queue(Cookie::forget('theme'));
Cookies Are Encrypted by Default
Laravel encrypts every cookie it creates. A visitor who opens their browser tools sees unreadable text instead of dark, and they cannot change the value, because Laravel would notice the change. This protection is done by a piece of middleware that is active by default. You will learn how middleware works in the next lessons.
This also has a side effect that surprises many beginners. A cookie that was not created by Laravel, for example one written by JavaScript, is not encrypted, so Laravel cannot read it and returns null. If JavaScript must set a cookie that your app reads, you can list its name as an exception in bootstrap/app.php, which is part of the Middleware lessons.
Sessions or Cookies?
Both remember something about a visitor, but they are used for different jobs. Here is a simple way to choose:
- Use a session for anything private or important, such as the logged-in user, a shopping cart or a multi-step form
- Use a session when the data may be larger than a few words
- Use a cookie for small, harmless preferences like theme or language
- Use a cookie when the preference should last for weeks, even after the session has expired
- Never put secrets, permissions or prices in a cookie
Remember that the session needs a cookie to work, since the session ID travels in one. The difference is where the actual data lives. A cookie keeps it in the browser, and a session keeps it on your server.
Common Mistakes
Mistake 1: The Sessions Table Does Not Exist
With the database driver, every request reads from the sessions table. If it is missing, you see an error such as:
SQLSTATE[HY000]: General error: 1 no such table: sessions
On MySQL, the message looks like this:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'invoice_app.sessions' doesn't exist
Run php artisan migrate to create the table. If your project was created without it, php artisan make:session-table generates the migration. The same error often appears right after pointing your .env file at a new, empty database.
Mistake 2: Creating a Cookie but Not Returning It
cookie('theme', 'dark', 60);
return redirect()->route('invoices.index');
The cookie() helper only builds a cookie object. Nothing is sent to the browser, so there is no error and no cookie. Attach it with ->cookie(...) on the response, or use Cookie::queue().
Mistake 3: Mixing Up Minutes and Seconds
->cookie('theme', 'dark', 3600);
Laravel expects minutes, so this cookie lasts about 2.5 days, and not one hour as you might expect. Write the sum out, like 60 * 24 * 30, so the meaning is clear.
Mistake 4: Reading a Cookie Set by JavaScript
A cookie like theme=dark written in the browser by JavaScript is not encrypted, so $request->cookie('theme') returns null. There is no error. Either set the cookie from Laravel, or add the name to the list of cookies that are not encrypted.
Mistake 5: Storing Large Objects or Secrets in the Session
Putting a full invoice list, a big file or a password in the session slows down every request and creates a security risk. Store a small identifier, such as the invoice number, and load the rest when needed.
Mistake 6: Using Sessions in API Routes
Routes in routes/api.php are stateless and do not use sessions. Data you store there will not be there on the next request, and no error tells you why. Mobile apps and API clients identify themselves with tokens, and you will learn how in the Sanctum lesson.
Quick Summary
- HTTP has no memory, so sessions and cookies are used to remember a visitor.
- A session keeps data on the server and identifies the visitor with an ID stored in a cookie.
- By default, Laravel stores sessions in the
sessionsdatabase table, and they expire after 120 idle minutes. - You can change the driver with
SESSION_DRIVERin.env. - Store a value with
session(['key' => 'value'])and read it withsession('key', 'default'). - Use
has(),exists(),forget(),pull(),flush()andpush()to work with session data. - Flash data from the last lesson is session data that is removed after one more request.
- A cookie is a small text stored in the browser and sent back on every request.
- Read a cookie with
$request->cookie(), write it with->cookie()on a response, and delete it withwithoutCookie(). - Cookie lifetimes are in minutes, and Laravel encrypts cookies by default.
- Use sessions for private or larger data, and cookies for small, harmless preferences.
What’s Next
You now know how Laravel remembers a visitor between requests. But so far, every request has been handled by the same code, without any checking along the way. What if you want to check that someone is logged in, or block certain visitors, before the controller even runs? In the next lesson, Middleware Basics, you will learn how requests can pass through checkpoints on their way to your controller.