Laravel Sessions

Since HTTP driven applications are stateless, sessions provide a way to store information about the user across multiple requests. Laravel comes with different session drivers to manage user sessions:

  • 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.
  • array - sessions are stored in a PHP array and will not be persisted.

The session configuration file is stored at config/session.php. By default, Laravel is configured to use the file session driver. To support faster sessions consider using memcached or redis in production environment.

How to store sessions in database?

To store session data in database first of all we will need to create a migration table. To create a session table and migrate it run following commands:

# First generate a migration file
php artisan session:table

# Now, migrate generated sessions table
php artisan migrate

Running first command will generate a sample migration file with following contents:

Schema::create('sessions', function ($table) {
    $table->string('id')->unique();
    $table->unsignedInteger('user_id')->nullable();
    $table->string('ip_address', 45)->nullable();
    $table->text('user_agent')->nullable();
    $table->text('payload');
    $table->integer('last_activity');
});

Once you have created migration open your .env  file and change following line:

SESSION_DRIVER=database

How to use redis session?

To store sessions in your redis store first of all you need to install redis driver. Open your terminal window and run following command to install redis driver:

composer require predis/predis

Now, open your .env file and change following line:

CACHE_DRIVER=redis
SESSION_DRIVER=redis

REDIS_CLIENT=predis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
REDIS_DB=0

Once you have configured redis configurations run following command to clear cache and enjoy redis cache/sesisons.

php artisan cache:clear

How to CRUD sessions

Once you have session configured you can now use some of the methods shown below to perform crud operation on session:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * Show the profile for the given user.
     *
     * @param  Request  $request
     * @return Response
     */
    public function show(Request $request)
    {
        // get all session data
        $data = $request->session()->all();

        // get current name field from the session
        $name = $request->session()->get('name');

        // get name from the session and if null use default value
        $name = $request->session()->get('name', 'default');

        // delete name from session array
        $request->session()->forget('name');

        // store name in session
        $request->session()->put('name', 'sandip');

        // add new key in session user array
        $request->session()->push('user.name', 'sandip');

        // pull a name field from the session and then delete it
        $name = $request->session()->pull('name', 'default');

        // add a flash message in current session
        $request->session()->flash('success', 'Task was successful!');

        // flush session data
        $request->session()->flush();

        // re-generate new session id
        $request->session()->regenerate();

        // The has method returns true if the item is present and is not null
        if ($request->session()->has('users')) {
            //
        }

        // The exists method returns true if the item is present
        // To determine if an item is present in the session, even if its value is null
        if ($request->session()->exists('users')) {
            //
        }
    }
}

I hope you like this tutorial if you do please share and spread your love to others.