Session not persist on Laravel 5.4

时光总嘲笑我的痴心妄想 提交于 2020-02-24 07:54:37

问题


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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/48290480/session-not-persist-on-laravel-5-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!