Articles

What are sessions in Laravel, configuration and use with examples

Laravel sessions allow you to store information, and exchange it between requests in your web application. 

They are an easy way to persist data for the current user. This tutorial will give you the basics of working with sessions in Laravel.

What is Laravel session

In Laravel, a session is a way to store information, to correctly handle requests made by a user. When a user starts a Laravel application, a session is automatically started for that user. 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 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 during the session on your application.

Session configuration in Laravel

To use sessions in Laravel, you must first enable them in the file config/session.php of configuration. In this file it is possible to set configuration parameters related to sessions. For example the duration of the session, the driver to use for storing the session data, and the storage location for the session data. 

The file has the following configuration options:
  • driver: Specifies the pre session driverdefiready to use. Laravel supports several session drivers: file, cookie, database, apc, memcached, redis, dynamodb, and array;
  • Lifetime: Specifies the number of minutes in which the session must be considered valid;
  • expire_on_close: If set to true, the session will expire when the user's browser is closed;
  • encrypt: true means that the framework will encrypt 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;
  • backgammon: If the database session driver is used, this option specifies the database table to use to store 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.

Below is an example of a file sessions.php with session duration 120 seconds, use of files stored in the directory framework/sessions:

<?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', null),
    'table' => 'sessions',
    'store' => env('SESSION_STORE', null),
    'lottery' => [2, 100],
    'cookie' => env(
        'SESSION_COOKIE',
        Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
    ),
    'path' => '/',
    'domain' => env('SESSION_DOMAIN', null),
    'secure' => env('SESSION_SECURE_COOKIE'),
    'http_only' => true,

    'same_site' => 'lax',

];

You can also configure the session using environment variables in the file .env. For example, to use the database session driver and store session data in a session table, with MySQL-type DB, you can set the following environment variables:

SESSION_DRIVER=database
SESSION_LIFETIME=120
SESSION_CONNECTION=mysql
SESSION_TABLE=sessions

Laravel session setup

There are three ways to work with session data in Laravel: 

  • using thehelper of global session;
  • using the Session facade;
  • through one Request instance

In all 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.

Innovation newsletter
Don't miss the most important news on innovation. Sign up to receive them by email.

Global Session Helper

In Laravel, using the function Global Session Helper it's a convenient way to access the session services provided by the framework. It allows you to store and retrieve data from session in your application. Here is an example of how to use the session helper:

// 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 pre valuedefinite as the second argument to the function session, which will be returned if the specified key is not found in the session:

$value = session('key', 'default');

Instance of Session Request

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.), request URL, headers of the request and the request body. It also contains various methods that can be used to retrieve and manipulate this information.

Typically you access the instance of the Session Request through the variable $request in a Laravel application. For example, a session can be accessed through a request instance using the helper function session().

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 this example, the variable  $request it is an instance of the class Illuminate\Http\Request, which represents the current HTTP request. The function session request instance returns an instance of the class Illuminate\Session\Store, which provides various functions for working with the session.

Ercole Palmeri

Innovation newsletter
Don't miss the most important news on innovation. Sign up to receive them by email.

Latest Articles

The Benefits of Coloring Pages for Children - a world of magic for all ages

Developing fine motor skills through coloring prepares children for more complex skills like writing. To color…

May 2, 2024

The Future is Here: How the Shipping Industry is Revolutionizing the Global Economy

The naval sector is a true global economic power, which has navigated towards a 150 billion market...

May 1, 2024

Publishers and OpenAI sign agreements to regulate the flow of information processed by Artificial Intelligence

Last Monday, the Financial Times announced a deal with OpenAI. FT licenses its world-class journalism…

April 30 2024

Online Payments: Here's How Streaming Services Make You Pay Forever

Millions of people pay for streaming services, paying monthly subscription fees. It is common opinion that you…

April 29 2024