Sessions and cache
A session keeps one visitor's data between requests: who is logged in, what is in the cart. A cache keeps the results of slow computations for all visitors at once. Both have a simple "put — get" interface.
Writing and reading the session
The session is used through the request object or the session() function:
$request->session()->put('cart', [1, 5, 9]);
$cart = $request->session()->get('cart', []);
session(['locale' => 'ru']);
$locale = session('locale', 'en');The second argument of get() is a default value.
Changing and removing
$request->session()->push('cart', 12); // add to an array
$request->session()->increment('visits'); // increase a counter
$request->session()->forget('cart'); // remove a key
$request->session()->flush(); // clear the sessionFlash messages
flash() keeps a value only until the next request — this is how a message is shown after a redirect:
$request->session()->flash('status', 'Profile updated');
return redirect('/profile')->with('status', 'Profile updated');@if (session('status'))
<div class="alert">{{ session('status') }}</div>
@endifWhere sessions are stored
The SESSION_DRIVER variable in .env sets the storage:
| Driver | Where the data lives |
|---|---|
database | A database table; the default |
file | Files in storage/framework/sessions |
redis | A Redis server — fast, for busy sites |
cookie | Encrypted cookies in the browser |
The cache
The result of a slow query is saved in the cache and served from there until it expires:
use Illuminate\Support\Facades\Cache;
Cache::put('settings', $settings, now()->addHour());
$settings = Cache::get('settings', []);remember
The method needed most often is remember(): it returns the value from the cache, and if it is not there, runs the function, saves the result and returns it:
$popular = Cache::remember('posts.popular', now()->addMinutes(10), function () {
return Post::orderByDesc('views')->take(5)->get();
});For ten minutes the database query does not run at all.
Clearing the cache
When the data changes, the entry is removed — the next access creates it again:
Cache::forget('posts.popular');A command clears the whole store:
php artisan cache:clearWhat to cache
Good candidates are data read often and changed rarely: site settings, menus, "popular" lists, responses from other APIs. A particular user's data is cached with their identifier in the key: "user.{$id}.stats".
Common mistake
A stale cache shows old data: a post was deleted, yet it still hangs in the "popular" block. Clear the entry in the same place where you change the data, or set a short lifetime. And do not cache "just in case": find the genuinely slow spot first.