简体   繁体   English

Laravel:会话未保存

[英]Laravel: Sessions not saving

So I've read through all the Laravel sessions information and all the stackoverflow questions about Laravel sessions but it's just no help. 因此,我已经阅读了所有Laravel会话信息以及有关Laravel会话的所有stackoverflow问题,但这无济于事。

Im trying to store the username when I'm logging in, and I want it to show the whole time I'm logged in on a page. 我正在尝试在登录时存储用户名,并且希望它显示我在页面上登录的整个时间。 Now when I login I get to the main page and the username shows, and I go back to login, which redirects me to the main page and the username is not there anymore. 现在,当我登录时,我进入主页,并显示用户名,然后返回登录,这将我重定向到主页,并且用户名不再存在。 The code I'm using: 我正在使用的代码:

Session::put('username', Input::get('username'));
$value = Session::get('username');
return View::make('main')->with('username',$value);

and then in my main.blade.php: 然后在我的main.blade.php中:

@if(!empty($username))
     {{$username}}
@endif

I have no idea what I'm doing wrong. 我不知道我在做什么错。 I'm doing it exactly like all the examples. 我正在像所有示例一样进行此操作。 What am I doing wrong here? 我在这里做错了什么?

If you're not doing it already, you should make use of Laravels Auth . 如果您尚未这样做,则应使用Laravels Auth Then you don't have to handle the stuff yourself and can just do this to retrieve the username: 然后,您不必自己处理这些东西,只需执行以下操作即可检索用户名:

Auth::user()->username;

Edit 编辑

The actual problem here weren't your sessions but the fact that you only passed the $username to the view in your one controller and not all the time when your rendered it. 此处的实际问题不是您的会话,而是您仅将$username传递给了一个控制器中的视图,而不是所有时间都将其传递给视图。

If you want some property of the current user, definitely use Auth::user()->username . 如果您想要当前用户的某些属性,请绝对使用Auth::user()->username If you have other session values you can access them directly in the view using: 如果您还有其他会话值,则可以使用以下方法直接在视图中访问它们:

{{ Session::get('foo'); }}

Another approach are view composers. 另一种方法是视图作曲家。 They let you pass something to the view every time it gets rendered: 它们使您可以在每次渲染视图时将某些内容传递给视图:

View::composer('main', function($view){
    $view->with('foo', Session::get('foo'));
});

You can put this code in app/filters.php or create a new app/composers.php and include it at the end of app/start/global.php with: 您可以将此代码放入app / filters.php或创建一个新的app / composers.php并将其包含在app / start / global.php的末尾,并包含以下内容:

require app_path().'/composers.php';

Now the variable always available in main.blade.php by just: 现在,变量始终可以在main.blade.php通过以下方式获得:

{{ $username }}

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

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