Home >PHP Framework >Laravel >CURD operation of session in laravel
HTTP protocol is stateless, so with cookie and session technology, they cooperate to maintain a state. It is very convenient to set and get sessions in laravel. Next, let’s take a look.
Configuration
The session is saved on the server. The default session is saved in a file on the server. However, this method is not very efficient. Currently, it is popular to save the session in a third-party database such as redis or memcached. These nosql reads and writes are very efficient and easier to manage. Next, let’s see how laravel configures the session
Laravel’s session configuration file is in config/session.php. In this configuration file, you can configure the session storage method, validity time, etc.
If you need to configure the storage method to redis, you need to modify the driver configuration item and change it to redis. In addition, it also supports local storage (default), relational database storage, etc.
Get the session value
First let’s look at how to get the session value, which can be obtained by responding to the session method of the instance request. The demo code is as follows:
$request->session()->get('key');
The second parameter of get this method is used to set the default value. If the corresponding session value is not obtained, the default value is returned. The demonstration code is as follows:
$request->session()->get('key', 'default');
The two parameters can also be a callback function, and a default value is returned through the callback function
$request->session()->get('key', function () { return 'default'; });
In addition to the above methods, it can also be obtained through the global session function. Their usage is consistent.
You can also obtain all session values at once through the all method, which returns an array:
$request->session()->all();
Laravel also provides a method to conveniently determine whether the session exists, using has Method
if ($request->session()->has('key')) {}
There is also an exists method. The difference between it and has is that has must exist and not be empty to return true, while exists returns true as long as it exists.
Set session value
There are two ways to set session. The following is the demo code:
$request->session()->put('key', 'val'); session(['key1' => 'val1', 'key2' => 'val2']);
Delete session value
You can delete the specified session through the forget method, and you can also delete all sessions through flush. The following is the demo code:
$request->session()->forget('k1'); $request->session()->forget(['k1', 'k2', 'k3']); $request->session()->flush();
Related recommendations: "laravel tutorial"
The above is the detailed content of CURD operation of session in laravel. For more information, please follow other related articles on the PHP Chinese website!