简体   繁体   English

Laravel如何知道某人是管理员还是普通用户-Laravel身份验证

[英]How does Laravel know if someone is an admin or normal user - Laravel Authentication

I am currently in the process of trying to understand how Laravel functions. 我目前正在尝试了解Laravel的功能。 And my biggest question is the authentication process. 我最大的问题是身份验证过程。 Lets say i have an admin panel and a user panel. 可以说我有一个管理面板和一个用户面板。 I have a column in the "users" table for "user_type" and 1 = normal user and 2 = admin user. 我在“用户”表中有一列“ user_type”,其中1 =普通用户,2 =管理员用户。 When a user logs into the user login form laravel checks the users info and makes sure that the type is 1 for a normal user login. 当用户登录到用户登录表单时,laravel会检查用户信息,并确保普通用户登录的类型为1。 If it is, it sets a session. 如果是,它将设置一个会话。 But how do i check if the user logged is a admin or normal user. 但是,如何检查登录的用户是管理员还是普通用户。 Any help is appreciated greatly! 任何帮助将不胜感激! :D :D

You can simply do: 您可以简单地执行以下操作:

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

Otherwise you can add a function in your User.php 否则,您可以在User.php添加一个函数

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

Then you can do the following: 然后,您可以执行以下操作:

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

First in your web.php you can do this: 首先,在您的web.php中,您可以执行以下操作:

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

And in your LoginController.php you can do something like this: 在您的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.
}

Of course you should extends this to include what if they user provided an invalid email, so you should redirect them back with the input and errors for example, hopefully this is similar to what you're looking for. 当然,您应该对此进行扩展,以包括如果用户提供了无效的电子邮件,该怎么办,因此您应该使用输入和错误将它们重定向回去,例如,希望这与您要查找的内容相似。

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

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