在 Laravel 4 中记住我

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17026764/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 07:56:02  来源:igfitidea点击:

Remember me in laravel 4

laravellaravel-4

提问by Victor

When I use

当我使用

Auth::attempt();

method to authenticate user I also put some user data in session, like user id, role, etc. And I put the session lifetime to zero. So, when user checks the "remember me" chechbox laravel remembers him even after he closed the browser. However, when he closes the browser I lost my session data. Although user is logged I don't have anymore some session data associated with him.

验证用户的方法 我还在会话中放置了一些用户数据,例如用户 ID、角色等。我将会话生存期设置为零。因此,当用户选中“记住我”时,即使关闭浏览器,laravel 也会记住他。但是,当他关闭浏览器时,我丢失了会话数据。尽管用户已登录,但我不再有一些与他相关的会话数据。

I tried this solution:

我试过这个解决方案:

Route::get('/', function() {
if (Auth::check()) {
    $user = Auth::user();

    Session::put('user_id',        $user->id);
    Session::put('company_id',     $user->company_id);
    Session::put('is_super_admin', Company::isSuperAdmin($user->company_id));
    Session::put('is_admin',       $user->is_admin);

    if (Session::get('is_super_admin')) {
        return View::make('admin');
    } else {
        return View::make('client');
    }
} else {
    return View::make('login');
}
});

And it works. However, it means that each time the logged user goes to somewhere where I should check if he's logged I must connect to DB, get user data and put it in session, so it's bad solution.

它有效。但是,这意味着每次登录的用户去某个地方我应该检查他是否登录时,我必须连接到数据库,获取用户数据并将其放入会话中,因此这是一个糟糕的解决方案。

But how can I remember my own user session details even after the browser is closed?

但是,即使在浏览器关闭后,我怎么能记住我自己的用户会话详细信息呢?

回答by Aloys

To use remember me in Laravel you should add an extra true boolean flag as an argument in Auth::attempt(). See the documentation: http://laravel.com/docs/security#authenticating-users

要在 Laravel 中使用记住我,您应该在Auth::attempt(). 请参阅文档:http: //laravel.com/docs/security#authenticating-users

if (Auth::attempt(array('email' => $email, 'password' => $password), true))
{
    // The user is being remembered...
}

Edit: Don't put your data in the session yourself. To Access that data use Auth::user()->field.

编辑:不要自己将数据放入会话中。要访问该数据,请使用Auth::user()->field.