Home » Session Not Working In Laravel

Session Not Working In Laravel

Last updated on December 24, 2020 by

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

  1. Go to “App/Http” and open Kernel.php file
  2. Add this line \Illuminate\Session\Middleware\StartSession::class, into the $middleware array. Please check the below screenshot.
Solution for session not working in Laravel

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:

  1. Specified Key Was Too Long Error In Laravel
  2. Run PHP Artisan Commands On Shared Hosting Servers
  3. How To Calculate Age From Birthdate
  4. Active Directory Using LDAP in PHP or Laravel
  5. How To Use The Laravel Soft Delete
  6. How To Add Laravel Next Prev Pagination
  7. cURL error 60: SSL certificate problem: unable to get local issuer certificate
  8. Difference between Events and Observers in Laravel
  9. Best Way to Remove Public from URL in Laravel
  10. 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!

 
 

5 thoughts on “Session Not Working In Laravel”

Leave a Comment

*

code