How to use a session in laravel 5.2 controller

I log in and then save the username in the session and then refresh this page, but the session does not save the 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
session
source share
4 answers

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

+2
source share

If use wants to use Session :: make sure you add the Facade session:

 use Session; 

Instead, you can use the session helper. So you can use the codes below:

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

See helpers for more details.

0
source share
 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 
0
source share

Remember one thing. When you submit a form using ajax in Laravel 5.2, there will be a CsrfTokenMismatch error. To avoid this, add your route name, which takes form values ​​using ajax in your application /Http/Middleware/VerifyCsrfToken.php in $ except array. Then this route will take on the values ​​of the form using an ajax request.

0
source share

All Articles