Reputation: 18347
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:
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
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
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