如何检查用户是否为管理员

如何检查用户是否为管理员

本文介绍了Laravel:如何检查用户是否为管理员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让用户成为管理员,该管理员将在站点条件的入口处检查==用户登录,如果是,则授予删除或编辑产品的权限.到目前为止,这是我的代码:

I want to make the user an administrator who at the entrance to the site conditions are checked == user login , if so then give the right to remove or edit product. This is my code so far:

@if(Auth::check())
   <p><a href="#" class="btn btn-success" role="button">Edite</a> <a href="#" class="btn btn-danger" role="button">Remove</a></p>
@endif

如何将Auth::check()等同于我的登录名?

How equate Auth::check() with my login?

推荐答案

首先,您需要创建包含角色详细信息的角色表. (我假设每个用户不仅可以具有管理员的角色,而且可以具有多个角色)

First of all you need to create the role table that contain the roles details. (I'm assuming Each user may have multiple roles not only Administrator)

角色表:

    Schema::create('role', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
    });

然后

role_user表

role_user Table

Schema::create('user_role', function (Blueprint $table) {
    $table->bigInteger('user_id')->unsigned();
    $table->integer('role_id')->unsigned();
    $table->foreign('user_id')
        ->references('id')->on('user');
    $table->foreign('role_id')
        ->references('id')->on('role');
});

创建角色模型:

然后将角色关系添加到用户模型

Afterwards add the roles relationship to the user model

class User extends Authenticatable {
    public function roles() {
        return $this->belongsToMany(Role::class, 'user_role');
    }
}

要检查用户是否具有管理员角色,您可以执行类似的操作

To check if user has Administrator role you can do something like

@if($user->roles()->where('name', 'Administrator')->exists())
enter code here
@endif

或者不用执行此语句,您可以将其作为函数放在用户模型中,如下所示:

Or instead of doing this statement you can put as function in the User model as below:

public function isAdministrator() {
   return $this->roles()->where('name', 'Administrator')->exists();
}

然后在模型中可以将其称为:

Then in your model you can call it:

@if(Auth::user()->isAdministrator())
enter code here
@endif

其他可能性(1-1)关系

首先在迁移中添加is_admin列

First add is_admin column in your migration

public function up()
{
    Schema::create('user', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->boolean('is_admin')->default(0);
        $table->rememberToken();
        $table->timestamps();
    });

然后您可以检查

@if($user->is_admin)

@endif

这篇关于Laravel:如何检查用户是否为管理员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 10:16