Session is a parameter-passing mechanism that helps to store data across multiple requests.
– Simply, it is the time devoted to a project. In a computer system, it starts when a user logs in the system and ends when he/she logs out from the system.
By default, Laravel sets up a session driver when the user creates a Laravel application. If a user wants to develop a Laravel application locally then it works fine but in the case of a production application, it might not perform proper functioning.
To improve the session performance, users can use Redis or Memcached. Users can change the session driver from the session.php
file in the 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'),
There are two methods for storing session values in Laravel. The 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 that uses using Request instance below:
// Request class instance
$request->session()->put(['key' => 'value']);
For inserting the values, push()
method is used in the Request instance:
$request->session()->push(['key' => 'value']);
There are various methods for getting session values which are:
$value = session('key');
$value = $request->session()->get('key');
The first method is using session()
whereas the second one is using request instance.
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.
– 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 the session array, flush()
method is used:
// Remove all values from session array
$request->session()->flush();
All Comments