Accessing session data in controller(Laravel)

喜你入骨 提交于 2019-12-14 03:35:20

问题


I have a page 'A'. I create a session variable on this page.

This page is then redirected to a function 'A' in a controller 'A' using window.location.

I try to access the session variable in the function 'A' using the following line

var_dump($request->session->get('variableSetOnPageA'));

This returns NULL.

Why? I need the 'variableSetOnPageA'.


回答1:


You can also get Session variable in Laravel like below in any of your function in Controller file:

$value = Session::get('variableSetOnPageA');

And you can set your Session variable like below in any of your function:

$variableSetOnPageA = "Can be anything";
Session::put('variableSetOnPageA',$variableSetOnPageA);

In your Controller file, make sure you add below code at top:

use Session;



回答2:


You ought to invoke the session method from \Illuminate\Http\Request:

$request->session()->get('foo')

or global helper function

session('foo')



回答3:


Important: It is very important that you call save function after you set any session value like this:

$request->session()->put('any-key', 'value');
$request->session()->save();    // This will actually store the value in session and it will be available then all over.

Check if you have $request available in the function.

public function A(Request $request)  // Notice Request $request here.
{
    $value = $request->session()->get('your-key');

    //
}



回答4:


This might be help you

if (session()->has('variableSetOnPageA')) {
  $result=session()->get('variableSetOnPageA')
}


来源:https://stackoverflow.com/questions/47986401/accessing-session-data-in-controllerlaravel

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