简体   繁体   English

如何在Laravel 5中使用会话

[英]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. 我正在尝试保存一些会话变量,但返回后laravel不保存会话变量。 Where is the problem in my code? 我的代码中的问题出在哪里?

in web.php: 在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);" 当我不使用“ 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.. 但是,当我尝试选择Cookie代码时不起作用。

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. 您无需手动启动会话,Laravel会为您维护会话。

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. 看看是否适合您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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