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

时间:2018-05-08 20:06:44

标签: php laravel authentication

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

2 个答案:

答案 0 :(得分:0)

您可以这样做:

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
}

答案 1 :(得分:0)

首先在你的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.
}

当然,您应该扩展这一点,以包括用户提供无效电子邮件的内容,因此您应该将输入和错误重定向回来,例如,希望这与您正在寻找的内容类似。

相关问题