Laravel sessions allow you to store data across requests in your web application. They are a simple way to persist data for the current user. This tutorial will cover the basics of working with sessions in Laravel.
What is a Laravel Session?
In Laravel, a session is a way to store data across multiple requests made by a user. When a user requests a Laravel application, a session starts automatically for that user. The session data is stored on the server, and a small cookie with a unique identifier is sent to the user's browser to identify the session.
You can use the session to store data that you want to use across multiple pages or requests. For example, you might use the session for user authentication or store other information that you want to use throughout the session on your application.
Session Configuration in Laravel
To use sessions in Laravel, you must first enable them in your config/session.php configuration file. In this file, you can alter the values of various options for how sessions should behave, such as the session's lifetime, the driver to use for storing the session data, and the storage path for the session data. The file has the following configuration options:
Configuration | Description |
---|---|
driver | Specifies the default session driver to use. Laravel supports several session drivers: file, cookie, database, apc, memcached, redis, dynamodb, and array. |
lifetime | Specifies the number of minutes the session should be considered valid. |
expire_on_close | If set to true , the session will expire when the user's browser is closed.
|
encrypt | If set to true , the framework will encrypt the session data before it is stored
|
files | If the file session driver is used, this option specifies the file storage location. |
connection | If the database session driver is used, this option specifies the database connection to use. |
table | If the database session driver is used, this option specifies the database table to use to store the session data. |
lottery | An array of values used to randomly select a session ID cookie value. |
cookie | This option specifies the name of the cookie that will be used to store the session ID. The path, domain, secure, http_only, and same_site options are used to configure the cookie settings for the session. |
Here's an example of a "config/session.php" file that is manually configured without using .env configuration. It uses the file session driver and stores session data in the "storage/framework/sessions" directory:
<?php
return [
'driver' => 'file',
'lifetime' => 120,
'expire_on_close' => false,
'encrypt' => false,
'files' => storage_path('framework/sessions'),
'connection' => null,
'table' => 'sessions',
'lottery' => [2, 100],
'cookie' => 'laravel_session',
'path' => '/',
'domain' => null,
'secure' => false,
'http_only' => true,
'same_site' => null,
];
You can also configure the session using environment variables in the .env file. For example, to use the database session driver and store session data in a sessions table in the MySQL database connection, you can set the following environment variables:
SESSION_DRIVER=database
SESSION_LIFETIME=120
SESSION_CONNECTION=mysql
SESSION_TABLE=sessions
Here is an example of the default session
configuration in Laravel 9x using the .env file:
<?php
use Illuminate\Support\Str;
return [
'driver' => env('SESSION_DRIVER', 'file'),
'lifetime' => env('SESSION_LIFETIME', 120),
'expire_on_close' => false,
'encrypt' => false,
'files' => storage_path('framework/sessions'),
'connection' => env('SESSION_CONNECTION'),
'table' => env('SESSION_TABLE'),
'store' => env('SESSION_STORE'),
'lottery' => [2, 100],
'cookie' => env(
'SESSION_COOKIE',
Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
),
'path' => '/',
'domain' => env('SESSION_DOMAIN'),
'secure' => env('SESSION_SECURE_COOKIE'),
'http_only' => true,
'same_site' => 'lax',
];
Setting Up Session in Laravel
There are three ways of working with session data in Laravel: Using the global session helper, Using the Session facade, and via a Request instance. In all of these cases, the data you store in the session will be available in subsequent requests made by the same user until the session expires or is manually destroyed.
The Global Session Helper
In Laravel, using the global session helper function is a convenient way to access the session services provided by the framework. It allows you to store and retrieve data from the session in your application. Here's an example of how to use the session
helper to store and retrieve data:
Example:
// Store data in the session
session(['key' => 'value']);
// Retrieve data from the session
$value = session('key');
// Remove data from the session
session()->forget('key');
// Clearing the Entire Session
session()->flush();
You can also pass a default value as the second argument to the session
function, which will be returned if the specified key is not found in the session:
$value = session('key', 'default');
The session
helper function is a shorthand for accessing the session services provided by Laravel. You can also access these services directly through the Session
facade or by injecting the Illuminate\Session\SessionManager
class into your controller or other class.
Session Request Instance
In Laravel, a session request instance refers to an object that represents an HTTP request and contains information about the request, such as the request method (GET, POST, PUT, etc.), the request URL, the request headers, and the request body. It also contains various methods that can be used to retrieve and manipulate this information.
The session request instance is typically accessed through the $request
variable in a Laravel application. For example, a session can be accessed via a Request instance using the session()
helper function.
Example:
<?php
use Illuminate\Http\Request;
class ExampleController extends Controller
{
public function example(Request $request)
{
// Store data in the session using the put function
$request->session()->put('key', 'value');
// Retrieve data from the session using the get function
$value = $request->session()->get('key');
// Check if a value exists in the session using the has function:
if ($request->session()->has('key')) {
// The key exists in the session.
}
// To determine if a value exists in the session, even if its value is null:
if ($request->session()->exists('users')) {
// The value exists in the session.
}
// Remove data from the session using the forget function
$request->session()->forget('key');
}
}
In the example above, the $request
variable is an instance of the Illuminate\Http\Request
class, which represents the current HTTP request. The session
function of the request instance returns an instance of the Illuminate\Session\Store
class, which provides various functions for working with the session.
Remember that the session must be started before you can use it. In Laravel, the session automatically starts for you, so you do not need to worry about starting it yourself.