How to use session in laravel 5.2 controller

百般思念 提交于 2019-12-24 16:48:49

问题


I login and then keep the username in a session, then I refresh this page, but the session not keep value.

This is my code:

class WelcomeCtrl extends Controller
{
     public function gotoWelcome()
     {   
         return view('welcome')->with('user',Session::get('user'));//nothing in session
     }

        public function dologin(){
                $username = $_POST['username'];
                $password = $_POST['password'];
                $result = "";
                if($username && $password){
                    $result = User::getUser($username, $password);
                    if($result){
                        Session::set('user',$result);
                        return response()->json([true, Session::get('user')]);//I get value expected, this is ok.
                    }
                }
                return response()->json([false, Session::get('user')]);     
            }
    }

回答1:


Have you added the middleware group 'web' to your routes. In 5.1 , this was default for all the routes and was used for session management and csrf verification etc.




回答2:


If use want to use Session:: make sure you add session Facade by:

use Session;

Instead of this you can use session helper. So you can use below codes:

session()->user()->email;
session()->get('user');
session()->flash('message', 'Hi there.');

For more see helpers.




回答3:


Session::put('key','value');//to put the session value
Session::get('key');//to get the session value

Session::has('key');//to check the session variable exist or not



回答4:


Remember one thing. When you post a form using ajax in Laravel 5.2, there will be a CsrfTokenMismatch error. To avoid this, add your route name which is accepting form values with ajax in your App/Http/Middleware/VerifyCsrfToken.php in $except array. Then that route will accept form values with ajax request.



来源:https://stackoverflow.com/questions/36952404/how-to-use-session-in-laravel-5-2-controller

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