Dran Dev
Dran Dev

Reputation: 519

Laravel - Sessions not storing properly / Not persisting?

In my Page A, I have:

session()->put('name','My Name');

and tests it via:

return session()->get('name');

And it displays My Name.

Now on my Page B, I returned the session:

return session()->get('name');

However now it displays null or " ". What am I doing wrong here?

PS: I'm using Laravel 5.7

Update

Here's my Page A where I call the session()->put:

if(Hash::check($password, $user->password)){
    session()->put('name', $user->name);
    return response()->json([
        'message' => 'Success! '.session()->get('name')
    ]);
}

This displays Success! My Name

But when I go to Page B and have a:

$thename = session()->get('name');
return 'name = '.$thename;

I get name =

And more so, if I set the name on Page B:

session()->put('name', 'ASDF');

After the first load it will say name = ASDF on Page B. I delete the line: session()->put('name', 'ASDF'); and refreshes the page, it still says name = ASDF so that means it's saving there.

If I go back to Page A, set the name again there, and go back to Page B, it still says name = ASDF not name = My Name

Upvotes: 2

Views: 2550

Answers (1)

Marc H.
Marc H.

Reputation: 432

Try manually saving the session (via ->save()) after writing to the session.

Example:

session()->put('name', $user->name);
session()->save();

If that seems to resolve it, you're killing Laravel's request lifecycle somewhere. Laravel uses middleware to save any session data, therefore all session data is persisted at the end of the request lifecycle.

Are you using dd somewhere?

Upvotes: 4

Related Questions