Sessions in Laravel

Contents
Store values
Flash data
Forget keys
Session drivers note

Store values

The session keeps small values for one visitor across requests. Put a value under a key, then read it back with a default for first-time visitors.

Store ids and preferences here, never passwords or other secrets.

session()->put("theme", "dark"); $theme = session("theme", "light");

Flash data

Flash stores a value for the next request only, then deletes it. It fits status notes after a redirect, like settings saved or profile updated.

Read it in the view once and it is gone on the request after that.

session()->flash("status", "Profile updated.");

Forget keys

Remove single keys when they are no longer needed, for example at logout. Forget drops one key, while flush drops the whole session.

Prefer forget so unrelated values survive the cleanup.

session()->forget("theme"); session()->flush();

Session drivers note

The driver decides where session data lives between requests. File works for one server, cookie keeps data in the browser, while database and Redis share sessions across servers.

Set the driver in the env file and leave the code as is.

SESSION_DRIVER=file

Next: CSRF

Article author: Arthur Isaev

Related articles
Development with PHP
What is Laravel and where it runs
Install Laravel
Your first route
Controllers
Blade basics
Blade advanced
Migrations
Eloquent models
Relationships
Query builder
Seeders and factories
Validation
Auth intro
Hand-rolled login
Middleware
Service container
Config and env
Artisan commands
Events and listeners
Queues
Mail
Cache
Sessions in Laravel
CSRF
Hashing
Sanctum tokens
API resources
Gates and policies
Notifications
Scheduler
Filesystem
Localization
Testing
HTTP tests
Collections
Carbon dates
Pagination
File uploads
Eloquent advanced
Transactions and locks
Deployment
Debugbar and dd
Broadcasting
Full-text search
Capstone: blog
Capstone: JSON API
Capstone: shop cart
Performance: kill N+1
Modern Laravel tour
Hero roadmap: the whole course on one page
Banner image

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: