简体   繁体   中英

How to use session in Laravel 5

I am trying to save some sessions variables but after return laravel does not save the session variable. Where is the problem in my code?

in web.php:

Route::get('/login', function(){
   return view(frontend.login);
 });
 Route::post('/login', function(Request $request){
   $control = "Some sql codes";
   if($control > 0){
       $user = "Some sql codes";
       $request->session()->start();
       $request->session()->put('user_id', $user->id);
       $request->session()->save();
       return view('frontend.logged_in);
   }
   else{
       return view('frontend.index);
   }
});

I know I should use controller but this is a temporary code and it should works fine here(am I right?). And when I do not use "return view('frontend.logged_in);" it saves the session variable but when I try to return it does not saves the session variable.

Note: If I choose 'file' for session driver theese codes are working just fine. But when I try to choose cookie codes doesn't work..

I believe it is because of the line:

$request->session()->start();

You dont need to manually start the session, Laravel maintains the session for you.

Use following code instead:

if($control > 0){
   $user = "Some sql codes";
   session(['user_id'=>$user->id]);
   return view('frontend.logged_in);
}

See if that works for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM