Session

Since HTTP driven applications are stateless, sessions provide a way to store information about the user across requests. Laravel ships with a variety of session back-ends available for use through a clean, unified API. Support for popular back-ends such as Memcached, , and databases is included out of the box.

The session configuration is stored in . Be sure to review the well documented options available to you in this file. By default, Laravel is configured to use the file session driver, which will work well for the majority of applications.

Before using Redis sessions with Laravel, you will need to install the predis/predis package (~1.0) via Composer.

Reserved Keys

The Laravel framework uses the flash session key internally, so you should not add an item to the session by that name.

The session may be accessed in several ways, via the HTTP request's session method, the Session facade, or the session helper function. When the session helper is called without arguments, it will return the entire session object. For example:

Storing An Item In The Session

  1. Session::put('key', 'value');
  2. session(['key' => 'value']);

Push A Value Onto An Array Session Value

  1. Session::push('user.teams', 'developers');

Retrieving An Item From The Session

  1. $value = session('key');

Retrieving An Item Or Returning A Default Value

  1. $value = Session::get('key', 'default');
  2. $value = Session::get('key', function() { return 'default'; });

Retrieving An Item And Forgetting It

Retrieving All Data From The Session

  1. $data = Session::all();

Determining If An Item Exists In The Session

  1. if (Session::has('users'))
  2. //
  3. }

Removing An Item From The Session

  1. Session::forget('key');

Removing All Items From The Session

  1. Session::flush();

Regenerating The Session ID

  1. Session::flash('key', 'value');

Reflashing The Current Flash Data For Another Request

  1. Session::reflash();

Reflashing Only A Subset Of Flash Data

When using the database session driver, you will need to setup a table to contain the session items. Below is an example Schema declaration for the table:

  1. Schema::create('sessions', function($table)
  2. {
  3. $table->string('id')->unique();
  4. $table->text('payload');
  5. $table->integer('last_activity');
  6. });

Of course, you may use the session:table Artisan command to generate this migration for you!

  • file - sessions will be stored in storage/framework/sessions.
  • cookie - sessions will be stored in secure, encrypted cookies.
  • database - sessions will be stored in a database used by your application.
  • memcached / redis - sessions will be stored in one of these fast, cached based stores.