Laravel Session

Sessions provide a way to store information about the user across multiple requests. Session configuration file is stored at config/session.php. Laravel provide various drivers like file, cookie, database, mechace / redis, dynamodb, array. By default, Laravel is configured to use file session driver.

Interaction with the Session

Retrieving Data

There are two primary ways to access the session data in laravel: the global session helper and via a Request instance. 

To access the session data via HTTP Request, we can use the get() method, which will take one argument, key to get the session data.

$request->session()->get('key');

When we retrieve an item from the session, we may also pass a default value as the second argument to the get method.

$request->session()->get('key', 'default');

To retrieve all the data in the session, we may use the all method:

$data = $request->session()->all();

To determine if an item is present in the session, we may use the has method:

if ($request->session()->has('users')) {
    //
}

Pushing To Array Session Value

The push method may use to push a new value onto a session value that is an array.

$request->session()->push('user.teams', 'developers');

Retrieving & Deleting An Item

The pull method may used to retrieve and delete an item form the session in a single statement:

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

If session data contains an integer we may wish to increment or decrement, we may use the increment and decrement methods.

$request->session()->increment('count');
$request->session()->decrement('count');

We may wish to store in the session for the next request. We may use the flash method.

$request->session()->flash('status', 'Task was successful!');

To remove a piece of data from the session. We may use forget method.

$request->session()->forget('name');

We may wish to remove multiple keys:

$request->session()->forget(['name', 'status']);

The Global Session Helper

You may also use the global session PHP function to retrieve and store data in the session.

Route::get('/home', function () {
// Retrieve a piece of data from the session...
  $value = session('key');

// Specifying a default value...
  $value = session('key', 'default');

// Store a piece of data in the session...
  session(['key' => 'value']);
});

By Ami



アプリ関連ニュース

お問い合わせはこちら

お問い合わせ・ご相談はお電話、またはお問い合わせフォームよりお受け付けいたしております。

tel. 06-6454-8833(平日 10:00~17:00)

お問い合わせフォーム