HTTP Session | Laravel 13.x - The clean stack for Artisans and agents
Skip to content HTTP Session Introduction Configuration Driver Prerequisites Interacting With the Session Retrieving Data Storing Data Flash Data Deleting Data Regenerating the Session ID Session Cache Session Blocking Adding Custom Session Drivers Implementing the Driver Registering the Driver Introduction Since HTTP driven applications are stateless, sessions provide a way to store information about the user across multiple requests.
That user information is typically placed in a persistent store / backend that can be accessed from subsequent requests. Laravel ships with a variety of session backends that are accessed through an expressive, unified API. Support for popular backends such as Memcached , Redis , and databases is included. Configuration Your application's session configuration file is stored at config/session.php . Be sure to review the options available to you in this file.
By default, Laravel is configured to use the database session driver. The session driver configuration option defines where session data will be stored for each request. Laravel includes a variety of drivers: file - sessions are stored in storage/framework/sessions . cookie - sessions are stored in secure, encrypted cookies. database - sessions are stored in a relational database. memcached / redis - sessions are stored in one of these fast, cache-based stores. dynamodb - sessions are stored in AWS DynamoDB. array - sessions are stored in a PHP array and will not be persisted.
The array driver is primarily used during testing and prevents the data stored in the session from being persisted. Driver Prerequisites Database When using the database session driver, you will need to ensure that you have a database table to contain the session data. Typically, this is included in Laravel's default 0001_01_01_000000_create_users_table.php database migration ; however, if for any reason you do not have a sessions table, you may use the make:session-table Artisan command to generate this migration: 1 php artisan make:session-table 2 3 php artisan migrate php artisan make:session-table php artisan migrate Redis Before using Redis sessions with Laravel, you will need to either install the PhpRedis PHP extension via PECL or install the predis/predis package via Composer.
For more information on configuring Redis, consult Laravel's Redis documentation . The SESSION_CONNECTION environment variable, or the connection option in the session.php configuration file, may be used to specify which Redis connection is used for session storage. Interacting With the Session Retrieving Data There are two primary ways of working with session data in Laravel: the global session helper and via a Request instance.
First, let's look at accessing the session via a Request instance, which can be type-hinted on a route closure or controller method. Remember, controller method dependencies are automatically injected via the Laravel service container : 1 <?php 2 3 namespace App\Http\Controllers; 4 5 use Illuminate\Http\ Request ; 6 use Illuminate\View\ View ; 7 8 class UserController extends Controller 9 { 10 /** 11 * Show the profile for the given user.
12 */ 13 public function show ( Request $request , string $id ) : View 14 { 15 $value = $request -> session () -> get ( ' key ' ); 16 17 // ... 18 19 $user = $this ->users-> find ( $id ); 20 21 return view ( ' user.profile ' , [ ' user ' => $ user ]); 22 } 23 } <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\View\View; class UserController extends Controller { /** * Show the profile for the given user. */ public function show(Request $request, string $id): View { $value = $request->session()->get('key'); // ... $user = $this->users->find($id); return view('user.profile', ['user' => $user]); } } When you retrieve an item from the session, you may also pass a default value as the second argument to the get method.
This default value will be returned if the specified key does not exist in the session. If you pass a closure as the default value to the get method and the requested key does not exist, the closure will be executed and its result returned: 1 $value = $request -> session () -> get ( ' key ' , ' default ' ); 2 3 $value = $request -> session () -> get ( ' key ' , function () { 4 return ' default ' ; 5 }); $value = $request->session()->get('key', 'default'); $value = $request->session()->get('key', function () { return 'default'; }); The Global Session Helper You may also use the global session PHP function to retrieve and store data in the session.
When the session helper is called with a single, string argument, it will return the value of that session key. When the helper is called with an array of key / value pairs, those values will be stored in the session: 1 Route :: get ( ' /home ' , function () { 2 // Retrieve a piece of data from the session... 3 $value = session ( ' key ' ); 4 5 // Specifying a default value... 6 $value = session ( ' key ' , ' default ' ); 7 8 // Store a piece of data in the session...
9 session ([ ' key ' => ' value ' ]); 10 }); Route::get('/home', function () { // Retrieve a piece of data from the session... $value = session('key'); // Specifying a default value... $value = session('key', 'default'); // Store a piece of data in the session... session(['key' => 'value']); }); There is little practical difference between using the session via an HTTP request instance versus using the global session helper.
Both methods are testable via the assertSessionHas method which is available in all of your test cases. Retrieving All Session Data If you would like to retrieve all the data in the session, you may use the all method: 1 $data = $request -> session () -> all (); $data = $request->session()->all(); Retrieving a Portion of the Session Data The only and except methods may be used to retrieve a subset of the session data: 1 $data = $request -> session () -> only ([ ' username ' , ' email ' ]); 2 3 $data = $request -> session () -> except ([ ' username ' , ' email ' ]); $data = $request->session()->only(['username', 'email']); $data = $request->session()->except(['username', 'email']); Determining if an Item Exists in the Session To determine if an item is present in the session, you may use the has method.
The has method returns true if the item is present and is not null : 1 if ( $request -> session () -> has ( ' users ' )) { 2 // ... 3 } if ($request->session()->has('users')) { // ... } To determine if an item is present in the session, even if its value is null , you may use the exists method: 1 if ( $request -> session () -> exists ( ' users ' )) { 2 // ... 3 } if ($request->session()->exists('users')) { // ... } To determine if an item is not present in the session, you may use the missing method.
The missing method returns true if the item is not present: 1 if ( $request -> session () -> missing ( ' users ' )) { 2 // ... 3 } if ($request->session()->missing('users')) { // ... } Storing Data To store data in the session, you will typically use the request instance's put method or the global session helper: 1 // Via a request instance... 2 $request -> session () -> put ( ' key ' , ' value ' ); 3 4 // Via the global "session" helper...
5 session ([ ' key ' => ' value ' ]); // Via a request instance... $request->session()->put('key', 'value'); // Via the global "session" helper... session(['key' => 'value']); Pushing to Array Session Values The push method may be used to push a new value onto a session value that is an array. For example, if the user.teams key contains an array of team names, you may push a new value onto the array like so: 1 $request -> session () -> push ( ' user.teams ' , ' developers ' ); $request->session()->push('user.teams', 'developers'); Retrieving and Deleting an Item The pull method will retrieve and delete an item from the session in a single statement: 1 $value = $request -> session () -> pull ( ' key ' , ' default ' ); $value = $request->session()->pull(
The rest of this page is on the live site.