Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Session not persist on Laravel 5.4

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

like image 743
Fabricio Avatar asked Jan 16 '18 21:01

Fabricio


2 Answers

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.

like image 143
Taher Mestiri Avatar answered Sep 20 '22 00:09

Taher Mestiri


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...

like image 35
igaster Avatar answered Sep 19 '22 00:09

igaster