I'm having some problems with Laravel Sessions, now I'm working under Laravel 5.4, so, I'm using this code for set session:
$request->session()->put('usuario', 'somevalue');
But when I'm trying to get the session value from another function on same controller with this code:
$request->session()->get('usuario');
I'm getting NULL, I'm trying importing Session and using "web" middleware
use Illuminate\Support\Facades\Session;
But I still getting same error.
Routes:
Route::group(['middleware' => 'web'], function () {
Route::post('login','UsuarioController@login');
Route::get('usuariodatos','UsuarioController@getDatos');
});
Controller, function login:
$data=$request->json()->all();
$user=Usuario::where('correo_electronico', $data['login_correo'])->first();
if(!empty($user->id_usuario)) {
if(Hash::check( $data['login_passwd'], $user->passwd) == true) {
$request->session()->put('usuario', $user);
$ses = $request->session()->get('usuario');
return json_encode(array("resultado" => $ses));
} else {
}
} else {
}
Controller function get session:
public function getDatos(Request $request)
{
return json_encode(array("resultado"=>$request->session()->get('usuario')));
}
Anyone can help me?
Thanks
You need to add : $request->session()->save();
after the put otherwise session will not persist.
It's strange that even in the official documentation this important detail doesn't exist.
Just remove the web
middleware. Since Laravel 5.3 it is applied by default to all routes. If you apply it manually then the session logic is executed twice and it will break.
A note on session()->save()
:
You don't need to call this if you are returning a Laravel response (ie view()
, response()
etc). Laravel will call this before returning the response. Again if you call this twice you might lose any flashed data from your session...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With