如何在Laravel Blade视图中检查用户是否为管理员

10

我有一个用户表如下:

+==============+
|     User     |
+==============+
|      id      |
+--------------+
|   firstname  |
+--------------+
|    lastname  |
+--------------+
|     email    |
+--------------+
|   password   |
+--------------+

以及一个角色表如下:

+==============+
|     Roles    |
+==============+
|      id      |
+--------------+
|     name     |
+--------------+

还有一个表来关联用户和角色:

+=============+
|  role_user  |
+=============+
|   user_id   |
+-------------+
|   role_id   |
+-------------+

如何检查当前登录的用户是管理员还是普通用户?


你需要首先创建表格或模型之间的关系。例如,用户有一个角色用户等。 - Emeka Mbah
你是否已经在用户和角色模型之间定义了多对多关系? - jedrzej.kurylo
5个回答

25
你需要在你的User模型中添加roles关联关系,就像这样:
public function roles() 
{
   return $this->belongsToMany(App\Role::class);
}

现在你需要像这样创建isAdmin用户:

public function isAdmin() 
{
   return in_array(1, $this->roles()->pluck('role_id')->all());
}

当您把管理员角色的ID设置为1时,它可以以其他方式定义,但一切都取决于它将如何使用。

也可以这样定义:

public function isAdmin() 
{
   return $this->roles()->where('role_id', 1)->first();
}

现在在您的 Blade 中,您可以执行:

@if (auth()->check())
   @if (auth()->user()->isAdmin())
      Hello Admin
   @else
      Hello standard user
   @endif
@endif

非常简单而且不错的答案。我也尝试了这个答案,它有效了。谢谢@MarcinNabialek。 - Ashok Adhikari
isAdmin() 应该写在 Model 还是 Controller 中? - stack
@stack 应该被添加到 User 模型中。 - Marcin Nabiałek
我收到一个错误 找不到类 'App\App\Role' 有什么想法吗? - aronccs
@aronccs 这是因为你的模型已经在 App 命名空间中,所以如果你在 App 命名空间中输入 App\Role,它将会查找 App\App\Role 类。Laravel 默认情况下(当你使用 artisan 命令创建时)会将你的模型放置在 App 命名空间中。 - TygerTy

7
这个简单的功能不需要数据库表 roles,也不需要使用 ACL。你只需添加额外的 tinyInteger 类型的 status 列,并为其添加数字,例如:
  • 0 = 禁用
  • 1 = 访客
  • 2 = 管理员
将以下代码添加到你的 User.php 中即可使其生效。
public function isDisabled ()
{
    return $this->statusCheck();
}

public function isVisitor ()
{
    return $this->statusCheck(1);
}

public function isAdmin ()
{
    return $this->statusCheck(2);
}

protected function statusCheck ($status = 0)
{
    return $this->status === $status ? true : false;
}

如果要在 blade 模板中进行检查,可以添加以下内容:

@if(Auth::user()->isDisabled())
    You are not Active
@elseif(Auth::user()->isVisitor())
    Welcome to example.com
@elseif(Auth::user()->isAdmin())
    Welcome Admin
@endif

此外,您可以创建 Blade 自定义指令,将此代码粘贴到 app/providers/AppServiceProvider.phpboot() 方法中。
// Blade custom directives for isAdmin

    Blade::directive('isAdmin', function() {
        return "<?php if(Auth::user()->isAdmin()): ?>";
    });

    Blade::directive('endisAdmin', function() {
        return "<?php endif; ?>";
    });

// Blade custom directives for isVisitor

    Blade::directive('isVisitor', function() {
        return "<?php if(Auth::user()->isVisitor()): ?>";
    });

    Blade::directive('endisVisitor', function() {
        return "<?php endif; ?>";
    });

// Blade custom directives for isDisabled

    Blade::directive('isDisabled', function() {
        return "<?php if(Auth::user()->isDisabled()): ?>";
    });

    Blade::directive('endisDisabled', function() {
        return "<?php endif; ?>";
    });

要调用此功能,您需要在Blade视图中编写以下代码:
@isAdmin()
     Welcome Admin
@endisAdmin

@isVisitor()
     Welcome to example.com
@endisVisitor

@isDisabled()
     Your are not active
@endisDisabled

简单来说, Laravel 提供了多种解决问题的方法,它只取决于你的需求和应用程序结构。

4

Role.php

use Illuminate\Database\Eloquent\Model;

class Role extends Model {

    protected $fillable = [
        'name'
    ];

    /**
     * A role can have many users.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function users() {

        return $this->belongsToMany('App\User');
    }

}

Then you can add this to User model:

public function isAdmin()
{
    foreach ($this->roles()->get() as $role)
    {
        if ($role->name == 'Admin')
        {
            return true;
        }
    }
}

View

@if(Auth::check())
    @if (Auth::user()->isAdmin())
        <h2>Admin user enter code here<h2>
    @endif
@endif


1

这些共享的方法是有效的。问题在于,如果您需要在页面上检查多次,它会多次访问数据库。例如,假设您有一个带有8个链接的导航菜单。第一、第四和第七个链接只应该由管理员可见。那么查询将会访问您的数据库3次。也许我有点过于苛求了,但这是重复的请求。

我正在尝试找到另一种方法来存储一个变量,以便在视图/模板中加载一次,这样每次需要检查是否为管理员时,都可以检查该变量,而不是每次都访问数据库。我已经通过控制器 -> 视图完成了这个操作,但仅限于模板中的视图。我正在考虑创建一个辅助方法并返回一个对象,以便在每个页面加载时只需检查一次。


-3

所以你有一个字段isAdmin,如果它是1,例如用户是管理员,否则就不是。当用户登录时,使用(Auth::user()->isAdmin == 1)检查,然后用户是管理员,否则就不是。

使用Auth::user()->,您可以检查当前已登录用户的用户表中的任何字段。

最好的问候


我需要为此编写任何方法吗? - Hoque MD Zahidul
没有 Laravel 的 Auth 方法,我假设你自己实现了登录等功能... 你可以通过 Auth::user()-> 检查任何东西,你使用了 Laravel 的用户模型吗? - MasterSith
@MasterSith,如果不在表之间创建模型关系,你的解决方案永远无法实现。 - Emeka Mbah
我假设他从一开始就使用了Laravel提供的用户模型。 - MasterSith

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接