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, Redis, and databases is included out of the box.
The session configuration is stored in app/config/session.php
. 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.
Session::put('key', 'value');
Session::push('user.teams', 'developers');
$value = Session::get('key');
$value = Session::get('key', 'default');
$value = Session::get('key', function() { return 'default'; });
$data = Session::all();
if (Session::has('users'))
{
//
}
Session::forget('key');
Session::flush();
Session::regenerate();
Sometimes you may wish to store items in the session only for the next request. You may do so using the Session::flash
method:
Session::flash('key', 'value');
Session::reflash();
Session::keep(array('username', 'email'));
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:
Schema::create('sessions', function($table)
{
$table->string('id')->unique();
$table->text('payload');
$table->integer('last_activity');
});
Of course, you may use the session:table
Artisan command to generate this migration for you!
php artisan session:table
composer dump-autoload
php artisan migrate
The session "driver" defines where session data will be stored for each request. Laravel ships with several great drivers out of the box:
file
- sessions will be stored inapp/storage/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.array
- sessions will be stored in a simple PHP array and will not be persisted across requests.
Note: The array driver is typically used for running unit tests, so no session data will be persisted.