Laravel Session
- 2021年4月02日
- 技術情報
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
asahi at 2021年04月02日 10:00:56