Laravel Session Management Tutorial

Laravel Session Management Tutorial

Laravel Session Tutorial
Laravel Session Tutorial

 

In this Laravel tutorial, we will have a detailed understanding of Laravel Session, basics of session management in the Laravel framework, how to create session variables, retrieve and save data to/from session variables.

Laravel provides simple interfaces to session managment using various session storage drivers. 

Basic Concepts of  Laravel Session

A Session is one of the primary storage for maintaining user information (in the form of session variables) to be accessible across multiple web pages. A Session in a web application is sometimes referred to as server-side web sessions. The client-side web sessions make use of client browser cookies to persist user information.

In nutshell, the session is a method to persist state between different web page requests. Laravel framework provides a very simple interface for session management in laravel.

List of available Session Drivers

Laravel framework allows developers to maintain user session using various storage. 

Laravel supports the following types of session drivers to store data:
1. file – sessions are stored in storage/framework/sessions.
2. Cookie – sessions are stored in secure, encrypted cookies.
3. Database – sessions are stored in your database.
4. Memcached – sessions are stored in one of these fast, cache-based stores.
5. In-memory Arrays – sessions are stored in a PHP array and will not be persisted.

If you are a beginner to Laravel Framework, then we recommend you to read the following topics:

How to configure Laravel Session environment?

By default, the session configuration file is stored at config/session.php.

The default session driver is “file”. The Memcached or Redis session driver provides better performance during multiple user requests.

Laravel Developers can configure all the session settings and drivers in config/session.php. Even we can choose whether or not to encrypt your session data, select which driver to use
(file is the default), and specify more connection-specific details like the length of
session storage and which files or database tables to use.

 

Session Config file sample code – ..config/session.php

/*
|————————————————————————–
| Default Session Driver
|————————————————————————–
|
| This option controls the default session “driver” that will be used on
| requests. By default, we will use the lightweight native driver but
| you may specify any of the other wonderful drivers provided here.
|
| Supported: “file”, “cookie”, “database”, “apc”,
| “memcached”, “redis”, “array”
|
*/

‘driver’ => env(‘SESSION_DRIVER’, ‘file’),

Accessing/Using Session Data

Laravel provides a unified interface to access, retrieve, save, and delete data from session variables. There are two ways to access the laravel session data – using the global session helper interface and Request instance.

The global session helper is a widely used method to read and write session data.

The unified API of the session management interface allows developers to save and retrieve session data based on individual keys, for example:

            session()->put(‘user_id’) and session()->get(‘user_id’)

Example using the global session() helper
             // retrieve session data
             $value = session()->get(‘key’);
             $value = session(‘key’);

             // save session data
             session()->put(‘key’, ‘value’); session([‘key’, ‘value’]);

Note – The session method can also be used on any Illuminate Laravel Request instance. Read about Laravel Request handling here.

Laravel Session Methods to retrieve, save and delete session data

There are two most common methods – get () and put(), but let’s take a complete look at each of
the available methods and their parameters:

The following is the list of methods available on session instances:

How retrieve session data in Laravel? laravel session example

The session()->get($key, $fallbackValue) method is used to retrieve session data. The get() method retrieves the value of the provided key out of the session. If there is no value attached to that key, it will return the fallback value instead (and if you don’t provide a fallback, it will return null).

The fallback value can be a string or a closure, as you can see in the following examples.
          $points = session()->get(‘blogs’);
          $points = session()->get(‘blogs’, 0);
          

Storing Data into Laravel Sessions

The session()->put($key, $value) method is used to store new value into the session data.
The put() method stores the provided value in the session at the provided key:
      session()->put(‘blogs’, 45);
     $points = session()->get(‘blogs’);

 

Pushing To Array Session Values

The session()->push($key, $value) is used to insert new values into the array.
If any of your session values are arrays, you can use push() to add a value onto
the array:
     session()->put(‘blogs’, [‘Laravel’, ‘WordPress’, ‘OpenCart’]);
     session()->push(‘blogs’, ‘Magento’);

How to determive if an item exists in Laravel Session

The session()->has($key) method is used to check whether there’s a value set at the provided key:
 

if (session()->has(‘points’)) {
    // do something
}

You can also pass an array of keys, and it only returns true if all of the keys exist.

If you face Laravel session not working error in your application, then refer the below articles:

Session not working in Laravel

Error creating a session in Laravel 5.3

Retrieving All Session Data

The session()->all() method returns an array of everything that’s in the session, including those values set by the framework. 

 

How to delete session data in Laravel? laravel session destroy

The session()->forget($key) and session()->flush() methods are used to remove a previously set session value. The flush() method removes every session value, even those set by the framework:
       session()->put(‘a’, ‘1’);
       session()->put(‘b’, ‘2’);
       session()->forget(‘a’);
      // a is no longer set, b is still set
       session()->flush();
      // after above statements, the session is now empty

Retrieving & Deleting session item at once

The session()->pull($key, $fallbackValue) pull() is the same as get(), except that it deletes the value from the session after pulling it.

Regenerating The Session ID

Due to security reasons, its always recommended that web application must regenerate the session ID frequently. This is achieved using the session()->regenerate() method.

NOTEThis is not a common activity, but if you need to regenerate your session ID, regenerate() is
there for you.

What is Laravel session lifetime?

The default session lifetime is 120 minutes i.e two hours. This is defined in the application’s config/session.php file.

/*
|————————————————————————–
| Session Lifetime
|————————————————————————–
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to immediately expire on the browser closing, set that option.
|
*/

‘lifetime’ => 120,

‘expire_on_close’ => false,

Endnotes!

Thanks for reading! Now that we have learned the basic concepts of Laravel Session, and how a session works in laravel. Then, we have explored the list of available session methods to retrieve, store and delete items from the session data.

Further Reading

Laravel 5.8 Session

What is a session in PHP?

Learn more about the session on Wiki page

Leave a Reply

Your email address will not be published. Required fields are marked *