在Laravel中进行身份验证时如何检查用户表中的参数?

在Laravel中进行身份验证时如何检查用户表中的参数?

问题描述:

I am trying to make a Laravel website that uses Laravel's Auth package. I'm using Laravel 5.3.2.

I have created a field in user table called role.

Now I want to know how to check the users role during the authentication process and then redirect to a required view based on the role. Please help me figure out how this would be possible.

Thank you very much in advance.

我正在尝试制作一个使用 Laravel的Auth包的Laravel网站。 我正在使用Laravel 5.3.2。 p>

我在用户表中创建了一个名为 role code>的字段。 p>

现在我想知道如何检查用户 身份验证过程中的角色,然后根据角色重定向到所需的视图。 请帮我弄清楚这是怎么可能的。 p>

非常感谢你提前。 p> div>

When a user logs in, this is done through your LoginController.php which is located at app\Http\Controllers\Auth

This controller uses a trait called AuthenticatesUsers.

This trait has a method called authenticated() which by default is empty. This method is called if it's not empty by the trait - after all the necessary loggin in stuff has been done.

You could override this method in your AuthenticationController.php and add the functionality you are asking for. An example would be:

// You actually get an Auth\User object passed to you by the trait!
public function authenticated(Request $request, $user)
{
    if($user->role == 'admin') {
        // You could do anything here
        return redirect()->route('admin-dashboard');
    } else {
        return redirect()->route('home');
    }
}

Beside solution overriding some default Laravel method. I suggest an other approach: redirect user to a route which is responsible for redirect user base on user's role

In AuthController

protected $redirectTo = '/redirect';

In routes

Route::get('redirect', function(){
    switch(auth()->user()->role){
        case 1:
            return redirect()->to();
        break;
        case 2:
            return redirect()->to();
        break;
    }
})