Session is a parameter passing mechanism which helps to store data across multiple requests. Simply, it is the time period devoted to a project. In computer system, it starts when a user logs in the system and ends when he/she log out from the system.
Session Driver in Laravel
By default, laravel sets up a session driver when the user creates laravel application. If a user wants to develop laravel application locally then it works fine but in case of production application, it might not give proper functioning.
For improving the session performance, user can use Redis or Memcached. User can change session driver from session.php file in config folder.
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option controls the default session "driver" that will be used on
| requests. By default, we will use the lightweight native driver but
| you may specify any of the other wonderful drivers provided here.
|
| Supported: "file", "cookie", "database", "apc",
| "memcached", "redis", "dynamodb", "array"
|
*/
'driver' => env('SESSION_DRIVER', 'file'),
How to use Laravel Session for storing data
There are two methods for storing session values in Laravel. First option is using session()
which is a helper function for storing data.
// Helper function
session(['key' => 'value']);
If the user doesn’t want to use this function then there is another method which is using Request instance below:
// Request class instance
$request->session()->put(['key' => 'value']);
Inserting Values in Session Array
For inserting the values, push()
method is used in Request instance.
$request->session()->push(['key' => 'value']);
Retrieving Session Value
There are various methods for getting session values which are:
Using Key
$value = session('key');
$value = $request->session()->get('key');
The first method is using session()
whereas the second one is using request instance.
Checking whether Session Array has value or not
has()
method can be used to determine whether the array has value or not.
// Checking if a session value exist
if ($request->session()->has('key') {
//
}
This returns true if the session has value whereas returns false if it is empty.
Deleting Session Values
If the user wants to remove specified values then the user can use forget()
method.
// Remove specified item from the session
$request->session()->forget('key');
For removing all values inside session array, flush()
method is used:
// Remove all values from session array $request->session()->flush();