【问题标题】:How does Laravel know if someone is an admin or normal user - Laravel AuthenticationLaravel 如何知道某人是管理员还是普通用户 - Laravel 身份验证
【发布时间】:2018-05-08 20:06:44
【问题描述】:

我目前正在尝试了解 Laravel 的功能。我最大的问题是身份验证过程。假设我有一个管理面板和一个用户面板。我在“users”表中有一个用于“user_type”的列,1 = 普通用户和 2 = 管理员用户。当用户登录用户登录表单时,laravel 会检查用户信息并确保类型为 1 以表示普通用户登录。如果是,它会设置一个会话。但是我如何检查登录的用户是管理员还是普通用户。非常感谢任何帮助! :D

【问题讨论】:

    标签: php laravel authentication


    【解决方案1】:

    首先在你的 web.php 中你可以这样做:

    Route::post('/login', 'Auth\LoginController@determineLoginType')->middleware('guest');
    

    在您的LoginController.php 中,您可以执行以下操作:

    public function determineLoginType(Request $request)
    {
        /** 
         * Here I am assuming that the email field on your user model is unique,
         * therefore I am retrieving that specific user by the email they provided 
         * at the login form
         */
    
        $user = \App\User::where('email', $request->email)->first();
    
        if ($user && $user->user_type == 2) { // Check if the user exists & check their type.
            return redirect('/admin-dashboard'); // If they're an admin redirect them to the admin dashboard.
        }
    
        return redirect('/home'); 
        // Otherwise proceed normally and redirect the user to the normal home or dashboard.
    }
    

    当然,如果用户提供了无效的电子邮件,您当然应该对此进行扩展,因此您应该使用输入和错误将他们重定向回来,希望这与您正在寻找的内容相似。

    【讨论】:

    • 也会检查一下。这看起来更像是我一直在寻找的东西:D
    【解决方案2】:

    你可以这样做:

    if (auth()->user()->user_type == 2) {
        // Do admin stuff
    }
    

    否则你可以在User.php中添加一个函数

    public function getIsAdminAttribute()
    {
        return $this->user_type == 2;
    }
    

    然后您可以执行以下操作:

    if (auth()->user()->is_admin) {
        // Do admin stuff
    }
    

    【讨论】:

    • 我会试试这个。所以有没有办法喜欢在控制器中这样做?就像当用户加载一个页面时,它会检查一个警卫或类似正常检查身份验证页面的东西?
    • @JarrodEstepp 是的,您可以在 Guard 中添加 if case。您也可以将其放入控制器中。取决于你想要达到的目标。
    • 只是快速浏览,不同的方式来做到这一点。我已经 2 周进入 laravel 并且还没有进行身份验证,因为我被困在这个以及如何使用用户名而不是电子邮件登录。
    猜你喜欢
    • 2016-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-08
    • 1970-01-01
    • 2018-05-12
    • 2015-08-04
    相关资源
    最近更新 更多