We recently faced an issue of the session not working in Laravel. This issue arose while adding or pushing an array into the Session. Let’s see some possible solutions to it.
Table of Contents |
1. Solution 01 : Session not Working in Laravel |
2. Alternate Solution For Session Not Working in Laravel |
3. Best Way Store Data in Session In Laravel |
Notes: Don’t use the die() or exit() to test the session because the die() or exit() does not let the Laravel script complete so that middleware not able to complete its process. To store session, middleware should complete its process.
Solution 01 Session not Working in Laravel
By default, web middleware provides a session start class to store the session state. Try to move your routes into the web middleware like below.
Route::group(['middleware' => ['web']], function () {
// add your all routes here to store session
});
That’s it. Let’s test the session now. It should start storing the session now. If it’s not, then please follow the other solution as below.
Alternate Solution
- Go to “App/Http” and open Kernel.php file
- Add this line
\Illuminate\Session\Middleware\StartSession::class
, into the $middleware array. Please check the below screenshot.
That’s it. Let’s test the session now. If you still have an issue then try the following way to store the data. We hope that helps.
Best Way Store Data in Session In Laravel
Try to use a global session helper function as below.
To Store An Array
Session::push('key', $array);
//or
session()->push('key', $array);
Store Session By Single Key
Session::put('session_key', 'value');
//or
session(['key'=>'value']);
Retrieving Session By Key
Session::get('key');
//or
session('key');
Get All Data From The Session
Session::all();
Additionally, read our guide:
- Specified Key Was Too Long Error In Laravel
- Run PHP Artisan Commands On Shared Hosting Servers
- How To Calculate Age From Birthdate
- Active Directory Using LDAP in PHP or Laravel
- How To Use The Laravel Soft Delete
- How To Add Laravel Next Prev Pagination
- cURL error 60: SSL certificate problem: unable to get local issuer certificate
- Difference between Events and Observers in Laravel
- Best Way to Remove Public from URL in Laravel
- Difference Between Factory And Seeders In Laravel
That’s it for now. We hope this article helped you to solve the session not working in Laravel issue.
Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you for reading this post. Keep Smiling 🙂 & Keep Coding!
Best Way to Remove Public from URL in Laravel | Scratch Code
Best Way to Remove Public from URL in Laravel | Scratch Code
Best Way to Remove Public from URL in Laravel | Scratch Code
using dd() is my problem. First note you wrote, ends one day confusing
Thank a lot
I am glad that my post is being helpful to you. Thanks 🙂