How to store Laravel sessions in database?

HTTP driven applications like Laravel are stateless, so here sessions provide us a way to store Laravel sessions in form of a user’s information regarding multiple requests. The user’s information is usually placed in a permanent store or backend location that can be acquired using subsequent requests.

Laravel has a variety of session backends that you can access through a meaningful, unified API.

A Laravel application’s session configuration file is in config/session.php. You should properly review the options present in this file. By default, Laravel uses the file session driver, this works best for many applications.

If you are using the database session driver, you will have to create a database table to store the session records. Let us go through the main steps involved to store Laravel sessions in a database.

Store laravel sessions in database

Step 1: Update .env

Firstly, check your database credentials in the .env file, to manipulate database structures in a Laravel application. You must change the default SESSION_DRIVER:file to SESSION_DRIVER:database to make the sessions get stored in the database instead of the file by default.


Then you must clear the cache using an artisan command as shown below.

php artisan optimize:clear

Step 2: Create sessions table

Secondly, create the table that will hold your session records. Pass in the migration command as shown below.

 php artisan make:migration user_sessions

Now, define the table columns in your migration file as shown below.

Schema::create('user_sessions', function ($table) {
    $table->string('ip_address', 45)->nullable();

Run migrate command as shown below to migrate the new sessions table.

php artisan migrate

Step 3: Store sessions

You will now have to store user sessions in the newly creates user_sessions table. Use the Request method in a Controller Class as shown below.

$request->session()->put('key', 'value');

You can use the Global session helper everywhere as shown below.

session(['key' => 'value']);

Step 4: Retrieve a session

There are three methods to pull a session detail, as shown below.

Method 1
$value = $request->session()->pull('key', 'default');

Method 2

Method 3

You can either get only key values or entire detail of a session. Save them to a variable or array and insert in the database accordingly.

Leave a Comment