What is a session
HTTP is a stateless protocol. That is, HTTP itself has no mechanism for retaining user information across requests. Laravel’s session feature provides a way to persist user data across multiple requests. Save data you want to persist across requests—login state, items in a cart, form input in progress—in the session.Session driver configuration
Session configuration lives inconfig/session.php.
You can switch drivers via the SESSION_DRIVER environment variable (in your .env file).
In Laravel’s default project setup, the
database driver is configured. Using the database driver requires a sessions table, but it’s included in the default migrations, so it works out of the box.Accessing the session
There are two ways to access the session: using methods on theRequest instance, or using the global session() helper.
Using the Request instance
Type-hintRequest on your controller method, then access the session via $request->session().
Using the global session() helper
The session() helper function can be called from anywhere—controllers, views, and so on.
Manipulating the session
Retrieving data
Checking whether data exists
has and exists.
Storing data
Removing data
Flash data
Flash data is session data that is only available for the next request. Use it for information you want to display just once, like form submission success messages or error messages.Storing data with flash()
Extending flash data
Displaying flash messages in Blade
Practical example: showing a message after form submission
After submitting a form, saving a success message to the session, redirecting, and displaying it on the next page is a classic web-application pattern.1
Define routes
2
Implement the controller
In the
store method that receives form submissions, redirect with a success message after saving.redirect()->with('success', '...') is a shortcut for passing flash data to the redirect target.3
Display the message in the layout
Add flash message display to
resources/views/layouts/app.blade.php.4
Create the index view
Pattern combined with validation errors
On validation failure, combine withback()->withErrors().
Laravel automatically flashes validation errors, so you can use the $errors variable in Blade.
Next steps
Validation
Learn how to validate form input data.