Retrieving Data
There are two primary ways of working with session data in Laravel: the global session helper and via a Request instance.$value = $request->session()->get('key');
$value = $request->session()->get('key', 'default');
$value = $request->session()->get('key', function () {
return 'default';
});
// Retrieve a piece of data from the session...
$value = session('key');
// Specifying a default value...
$value = session('key', 'default');
$data = $request->session()->all();
The has method returns true if the item is present and is not null
if ($request->session()->has('users')) {
//
}
The exists method returns true if the item is present, even if its value is null:
if ($request->session()->exists('users')) {
//
}
Storing Data
// Via a request instance...
$request->session()->put('key', 'value');
// Via the global helper...
session(['key' => 'value']);
Pushing To Array Session Values
The push method may be used to push a new value onto a session value that is an array. For example, if the user.teams key contains an array of team names, you may push a new value onto the array like so:
$request->session()->push('user.teams', 'developers');
Retrieving & Deleting An Item
The pull method will retrieve and delete an item from the session in a single statement:
$value = $request->session()->pull('key', 'default');
Flash Data
store items in the session only for the next request
$request->session()->flash('status', 'Task was successful!');
If you need to keep your flash data around for several requests, you may use the reflash method, which will keep all of the flash data for an additional request. If you only need to keep specific flash data, you may use the keep method:
$request->session()->reflash();
$request->session()->keep(['username', 'email']);
Deleting Data
The forget method will remove a piece of data from the session. If you would like to remove all data from the session, you may use the flush method:
// Forget a single key...
$request->session()->forget('key');
// Forget multiple keys...
$request->session()->forget(['key1', 'key2']);
$request->session()->flush();
0 件のコメント:
コメントを投稿