Laravel Tutorial - Laravel Session
Published January 29, 2022In this post, we are going to discuss the two primary ways of working with the session data in Laravel. Generally Session is used to store data about the user while making the requests inside the application or browser. Basically Laravel provides the storage drivers like file, apc, array,cookie, Memcached and databases. Laravel by default use file driver and this will be placed under config/session.php.
Two ways of session management in Laravel
-
Through the global session helper
-
Through the Request Instance
1.Through the global session helper
To create a session and store data in Laravel through the global session helper, we use the following simple syntax
session(['key' => 'value']); |
2. Through the Request Instance
Create Session
To create a session and store data in Laravel through the Request Instance, we use the following simple syntax
$request->session()->put('key', 'value'); |
Update session data
To update the session value, we use the following method:
$request->session()->push('user.uploadProfilePic', true); |
Accessing session data:
To access session data we first need to create instance of the session request, then call get method to fetcht the data.
$data= $request->session()->get('key'); |
We can also fetch all the data from the session by calling all() method on session instance
$data = $request->session()->all(); |
Delete Session Data
To delete data from Session we need to call forget() method on session object.
$request->session()->forget('key'); |
To delete all the data from session we can use flush() method on session instance.
We can also use pull() method to retrive the data from session then delete it.
Then what is the difference between forget() and pull() method to delete the data from the session,
when we use forget() method to delete the data it never return any value of the session, where as pull() method will retrive the data then delete data from the session.
Article Contributed By :
|
|
|
|
350 Views |