How to store, retrieve and delete session data in laravel

In Web Development, storing data in session is a common practice. The session will store browser-specific data on a server. It makes it easy to handle data without storing it in a database.

The session is useful to protect the data that the user wouldn't be able to read or write. Sessions are one of the secure and easy ways to store data. Nowadays it's common to store login status and user data in session and retrieve them whenever required. Before starting let's understand what is session.

What is a Session?

A session is the total time devoted to a particular task activity. In web development, the use session begins when the user logs in and it will end after a pre-defined time like 60 minutes or other if the user doesn't perform any activity. A session cookie is used in web pages for storing general information in case the user leaves the web page or browser. If a user comes back at in specific time then it will use that session information to provide a better user experience.

Laravel has in-built session functions which will help you to develop great functionality. Laravel provides various drivers like file, cookie, array, Memcached, Redis, and database to handle session data. This means we can store session data into one of those types like if we have configured session storing as a file then it will automatically store data into files.

Below are some of Laravel's session drives with a short description:

  • File: Session data are stored in files at storage/framework/sessions.
  • Database: It will store information in a database table.
  • Cookie: Data is stored in secure, encrypted cookies.
  • Redis / Memcached: Session data is stored in fast cache-based storage.
  • Dynamodb: Sessions information is stored in AWS DynamoDB.
  • array: sessions are stored in a PHP array.

You can use any above drivers to store session data. But you need to configure it before using it. The default driver for the application is either session or file.

All session-related configuration data is stored in config/session.php file like a driver, lifetime, encrypted or not, storage path, and more. Let's have a look at the configuration 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', 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',

];

For this example, we will use a database as a driver. So we need to create a session table in our database. Let's assume your application is running with proper database configuration and continue. Here, we will use the session: table command to generate a migration file for the session table. It's an in-built command to create a session migration file.

php artisan session:table

It will automatically create a new file in the migration directory. let's migrate it using the below command:

php artisan migrate

Access Session Functionality In Laravel

There are two ways to access session functionality in Laravel.

  1. Global Helper
  2. Request Instance

While using global helper we don't need to create any dependencies to use session functions. On other hand, we need to pass Request instances to our functions and access functions using object methods. Further, we will take both methods examples to store, retrieve or delete session data.

For this tutorial, we have created a controller to perform operations. You can use any controller as per your requirement.

Retrieving Session Data In Laravel

Let's assume, we have stored the user's name in the session variable and we will retrieve it using both methods.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class SessionTestController extends Controller
{
    public function getSessionData(Request $request){
        //Global Helper
        $value = session('user_name');
        $defaultValue = session('user_name', 'default');

        //Request Instance
        $value = $request->session()->get('user_name');
        $defaultValue = $request->session()->get('user_name', 'default');
    }
}

In the above example, the getSessionData() function will get the user name from the session using global and request methods. Here we have also shared an example to get the default value in case the user name is not found.

Here, we have just gotten a specific value from the session. But you can get all data from session using the below example:

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

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

Both methods will return all session data in Laravel. you can use it according to your requirements.

Store Data In Session Laravel

To store data in session we can either use request instance's put method or global session helper. You can store any type of data in a session like string, array, or JSON data. Let's take an example of storing data in a session.

public function storeSessionData(Request $request){
    //Global Helper
    session(['role'=> 'Admin']);

    //Request Instance
    $request->session()->put('role', 'Admin');
}

Here while using global helper we pass data into key and value pairs. While using the request instance we will pass name and value as parameters.

You can also use the push method to push a new value onto a session value which is an array.

Deleting Session Data In Laravel

They forget() or flush() methods to delete session data. The forget method is used to delete specific values from session while the other hand flush method will delete all session data.

With forget method, you can delete multiple values from session. Please See below example to delete session data.

public function deleteSessionData(Request $request){
    //Global Helper
    session()->forget('user_name');
    session()->flush();

    //Request Instance
    $request->session()->forget(['user_name', 'role']);
    $request->session()->flush();
}

Flash Session Data In Laravel

Sometimes we need to store some data and it's required just for a single request then we can use flash() method. The flash method will store a particular value in a session for one-time use and automatically delete it after first retrieval. An example of flash data is showing user messages like login success.

$request->session()->flash('status', 'Successfully logged in as user.');

Conclusion

Here, we have taken some examples to store, retrieve, delete, and flash data into a session in Laravel. But there are plenty of other methods for a session like checking session has a particular value, or a particular key exists in session data, increment or decrement session value, and more. We will learn more about them in further tutorials.