Docs Menu
Docs Home
/ / /
Laravel MongoDB

HTTP Sessions

On this page

  • Overview
  • Register a Session

In this guide, you can learn how to set up HTTP sessions by using Laravel MongoDB. Sessions allow your application to store information about a user across multiple server requests. Your application stores this information in a specified location that it can access in future requests that the user makes. The session driver in Laravel MongoDB uses the MongoDbSessionHandler class from the Symfony framework to store session information.

To learn more about support for sessions, see HTTP Session in the Laravel documentation.

Before you can register a session, you must configure your connection to MongoDB in your application's config/database.php file. To learn how to set up this connection, see the Configure Your MongoDB Connection step of the Quick Start guide.

Next, you can select the session driver and connection in one of the following ways:

  1. In an .env file, by setting the following environment variables:

    .env
    SESSION_DRIVER=mongodb
    # Optional, this is the default value
    SESSION_CONNECTION=mongodb
  2. In the config/session.php file, as shown in the following code:

    config/session.php
    <?php return [
    'driver' => 'mongodb', // Required
    'connection' => 'mongodb', // Database connection name, default is "mongodb"
    'table' => 'sessions', // Collection name, default is "sessions"
    'lifetime' => null, // TTL of session in minutes, default is 120
    'options' => [] // Other driver options
    ];

The following list describes other driver options that you can set in the options array:

  • id_field: Custom field name for storing the session ID (default: _id)

  • data_field: Custom field name for storing the session data (default: data)

  • time_field: Custom field name for storing the timestamp (default: time)

  • expiry_field: Custom field name for storing the expiry timestamp (default: expires_at)

  • ttl: Time to live in seconds

We recommend that you create an index on the expiry_field field for garbage collection. You can also automatically expire sessions in the database by creating a TTL index on the collection that stores session information.

You can use the Schema builder to create a TTL index, as shown in the following code:

Schema::create('sessions', function (Blueprint $collection) {
$collection->expire('expires_at', 0);
});

Setting the time value to 0 in the index definition instructs MongoDB to expire documents at the clock time specified in the expires_at field.

To learn more about using the Schema builder to create indexes, see the Create Sparse, TTL, and Unique Indexes section of the Schema Builder guide.

To learn more about TTL indexes, see Expire Data from Collections by Setting TTL in the Server manual.

Back

Scout Integration