夏期劇場
夏期劇場

Reputation: 18347

Laravel 5.2 : Session values doesn't persist across different routes?

I'm using Laravel 5.2. (And i'm a new Laravel user)

I need to use Session. And of course, read the Session Values from different Routes/pages. Here is the simple concept, simply:

  1. Save some session values from a route.
  2. Retrieve the values from another different route.

Here's the code i used.

Route::get('write', function () {
    session()->put('food', 'banana');
    session()->save();
    echo session()->get('food'); // <------ Shows: 'banana'
});

Route::get('read', function () {
    echo session()->get('food'); // <------ Shows nothing*
});

Thanks all.

Upvotes: 1

Views: 192

Answers (2)

Gino Pane
Gino Pane

Reputation: 5011

The reason is that session()->pull() actually pulls an element from the session and deletes it from session. So after /write called you'll have nothing in you session. That's why /read can not pull anything.

You should use session()->get('food') in your scenario instead of pull. Also make sure that your routes use web middleware.

Route::group(['middleware' => ['web']], function () {
    Route::get('write', function () {
        session()->put('food', 'banana');
        echo session()->get('food'); // <------ Shows: 'banana'
    });

    Route::get('read', function () {
        echo session()->get('food'); // <------ Shows 'banana' too
    });
});

Also check the official documentation for further read: https://laravel.com/docs/5.2/session.

Upvotes: 1

Tschallacka
Tschallacka

Reputation: 28742

use session()->save() after you put or modify something in it.

I usually do it via the facade Session::save();

If it isn't saved the session object wont know about it.

Upvotes: 0

Related Questions