12 Laravel 11 Basics: Session

Anis MarrouchiAI Bot
By Anis Marrouchi & AI Bot ·

Loading the Text to Speech Audio Player...

Since HTTP-driven applications are stateless, sessions provide a way to store information about the user across multiple requests. This tutorial covers the basics of session management in Laravel 11.

Configuration

Your application's session configuration file is stored at config/session.php. By default, Laravel uses the database session driver. The session driver configuration option defines where session data will be stored for each request. Laravel includes several 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. This driver is primarily used during testing.

Driver Prerequisites

Database

When using the database session driver, you need a database table to contain the session data. If you do not have a sessions table, use the make:session-table Artisan command to generate this migration:

php artisan make:session-table
php artisan migrate

Redis

Before using Redis sessions, install the PhpRedis PHP extension via PECL or the predis/predis package via Composer. For more information, consult Laravel's Redis documentation.

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.

// Using the Request instance
session()->get('key');
 
// Using the global session helper
$value = session('key');
$value = session('key', 'default');
session(['key' => 'value']);

Retrieving All Session Data

Use the all method to retrieve all session data:

$data = $request->session()->all();

Retrieving a Portion of the Session Data

Use the only and except methods to retrieve a subset of session data:

$data = $request->session()->only(['username', 'email']);
$data = $request->session()->except(['username', 'email']);

Determining if an Item Exists in the Session

Use the has, exists, and missing methods to check if an item is present in the session:

if ($request->session()->has('users')) {
  // ...
}
if ($request->session()->exists('users')) {
  // ...
}
if ($request->session()->missing('users')) {
  // ...
}

Storing Data

Use the put method or the global session helper to store data in the session:

$request->session()->put('key', 'value');
session(['key' => 'value']);

Pushing to Array Session Values

Use the push method to add a new value to an array session value:

$request->session()->push('user.teams', 'developers');

Retrieving and Deleting an Item

Use the pull method to retrieve and delete an item from the session in a single statement:

$value = $request->session()->pull('key', 'default');
``>
</Code>
 
### Incrementing and Decrementing Session Values
 
Use the `increment` and `decrement` methods for session data containing integers:
 
<Code>
```php
$request->session()->increment('count');
$request->session()->decrement('count');

Flash Data

Use the flash method to store items in the session for the next request:

$request->session()->flash('status', 'Task was successful!');
$request->session()->reflash();
$request->session()->keep(['username', 'email']);

Deleting Data

Use the forget method to remove a piece of data from the session or the flush method to remove all data:

$request->session()->forget('name');
$request->session()->forget(['name', 'status']);
$request->session()->flush();

Regenerating the Session ID

Use the regenerate method to regenerate the session ID:

$request->session()->regenerate();

Session Blocking

To utilize session blocking, your application must use a cache driver that supports atomic locks. Use the block method to limit concurrent requests for a given session:

Route::post('/profile', function () {
  // ...
})->block($lockSeconds = 10, $waitSeconds = 10);

Adding Custom Session Drivers

Implementing the Driver

If none of the existing session drivers fit your application's needs, Laravel makes it possible to write your own session handler. Your custom session driver should implement PHP's built-in SessionHandlerInterface.

For more detailed information, refer to the official Laravel Session documentation.

Learn more about session management in Laravel 11 and enhance your application's user experience. Check out the official documentation for more examples and advanced usage.


Want to read more tutorials? Check out our latest tutorial on Revolutionizing Customer Engagement: Twilio's AI-Powered Virtual Agents.

Discuss Your Project with Us

We're here to help with your web development needs. Schedule a call to discuss your project and how we can assist you.

Let's find the best solutions for your needs.