Laravel SessionsLaravel session is a way of storing the user information across the multiple user requests. It keeps track of all the users that visit the application. Let's understand the session through an example.
form.blade.php
Output When we click on the submit button, then the screen appears which is shown below: Storing the data in a sessionTo store the user name in a session, we use the put() method of session as shown below: $request->session()->put('user', $request->input('username')); To retrieve the session, we use the get() method of session as shown below: echo $request->session()->get('user'); Output Global Session HelperWe can also use the global session function that stores and retrieves the value in a session. When the session function is passed with a single parameter, then it returns the value of the key. If the session is passed with an array of key/value pairs, then the values are stored in the session. // Retrieve a data from the session key. $data=session('key'); //Providing a default value to the session key. $data=session('key', 'default'); // Storing the value in the session key. session(['key'=>'value']); Let's understand through an example. FormController.php Output Retrieving all session dataIf we want to retrieve all the session data, then we can use the all() method as shown below: $session_data = $request->session()->all(); Let's understand through an example: FormController.php Now, we define the route in web.php file. Route::get('/show','FormController@store'); Output Deleting the sessionNow, we will see how to delete the data from the session. We can delete the session by using the forget() method. Let's understand through an example. FormController.php Output In the above screenshot, we can see that the user1 is not displayed, so it means that the user1 has been deleted from the session. To remove all the data from the session, then we will use the flush() method. $request->session()->flush(); Let's understand the flush() method through an example. Output In the above screenshot, we observe that all the data has been removed from the session, and it returns an empty array. Flashing dataFlash data is useful when we want to store the data in the session for the current request as the flashed data is removed in the next request. Let's understand flashing data through an example. Output When we remove the flash() function from the code, then the code would look like: When we refresh the page twice, then on the second refresh, the session data will be deleted. Note: |