如何在 laravel 刀片视图中检查用户是否为管理员

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34680911/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:00:55  来源:igfitidea点击:

How to check user is Admin or not in laravel blade view

laraveleloquentlaravel-5.1

提问by Hoque MD Zahidul

I have

我有

User table like

用户表如

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

and my roles table

和我的角色表

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

and my role_user table is

我的 role_user 表是

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

How can I check current logged user is admin or normal user?

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

采纳答案by Hoque MD Zahidul

Role.php

角色.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:

然后您可以将其添加到User 模型中

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

回答by Marcin Nabia?ek

You need to add rolesrelationship in your Usermodel like so:

您需要rolesUser模型中添加关系,如下所示:

public function roles() 
{
   return $this->belongsToMany(App\Role::class);
}

and now you need to create isAdminuser like so:

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

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

As 1you put id of your admin role. Of course it could be also defined in other way, but everything depends on how this will be used.

1您输入管理员角色的 id 时。当然,它也可以用其他方式定义,但一切都取决于如何使用它。

It could be also defined this way:

也可以这样定义:

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

and now in your Blade you can do:

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

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

回答by Haider Lasani

It's not an ACLfor this simple functionality you don't even need a database table rolesyou can add extra tinyIntegerstatuscolumn and add numbers for example:

它不是用于此简单功能的ACL,您甚至不需要数据库表,roles您可以添加额外的tinyIntegerstatus列并添加数字,例如:

  • 0 = Disabled
  • 1 = Visitor
  • 2 = Admin.
  • 0 = 禁用
  • 1 = 访客
  • 2 = 管理员。

To make it functional add following code to your User.php.

要使其正常运行,请将以下代码添加到您的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;
}

To check in bladetemplate you can add

要签入blade模板,您可以添加

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

Moreover you can make blade custom directives, paste this code to your app/providers/AppServiceProvider.phpin boot()method.

此外,您可以制作刀片自定义指令,将此代码粘贴到您的app/providers/AppServiceProvider.phpinboot()方法中。

// 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; ?>";
    });

To call this you use need to write following lines in your blade view

要调用它,您需要在您的 blade view

@isAdmin()
     Welcome Admin
@endisAdmin

@isVisitor()
     Welcome to example.com
@endisVisitor

@isDisabled()
     Your are not active
@endisDisabled

In short laravel provides you a number of ways to solve a problem, it just depend on your need and application structure.

简而言之,laravel 为您提供了多种解决问题的方法,这取决于您的需求和应用程序结构。

回答by w1n78

the methods shared works. the problem is if you have to check more than once per page, it hits the database that many times. for instance, let's say you have a navigation with 8 links. the first, fourth, and seventh links should only be visible by admin only. that query will hit your database 3x. maybe i'm just anal but it's a duplicated request.

共享的方法有效。问题是,如果您必须每页检查多次,它会多次访问数据库。例如,假设您有一个带有 8 个链接的导航。第一个、第四个和第七个链接应该只有管理员可见。该查询将访问您的数据库 3 倍。也许我只是肛门,但这是一个重复的请求。

i'm trying to find another way to store a variable that loads once in the view/template so that every time i need to check if it's an admin, i check the variable and not hit the database every time. i've done it via controller -> view, but not just view alone in a template. i'm thinking of creating a helper method and returning an object to be checked once per page load.

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

回答by MasterSith

So you have some field isAdmin if it is 1 for example user is admin if not it is not. When user is loged check with (Auth::user()->isAdmin == 1)then user is admin else it is not

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

with Auth::user()->u can check any field from user table of current logged user.

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

Best Regards

此致