【问题标题】:Using Middleware to Obtain Admin Permissions使用中间件获取管理员权限
【发布时间】:2018-10-23 20:32:07
【问题描述】:

当我尝试编写管理规则以阻止用户输入特定路线时,我收到此错误:此集合实例上不存在属性 [名称]。

用户模型

<?php

public function roles()
{
    return $this->belongsToMany(Role::class, 'role_user', 'user_id', 'role_id');
}

public function isAdmin()
{
    if ($this->roles->name == "Admin") {
        return true;
    }
    return false;
}

管理中间件

public function handle($request, Closure $next) 
{

   if (Auth::check()) {
       if (Auth::user()->isAdmin()) {
       return $next($request);
       }
    }
    return redirect('/');
 }

路由和控制器

Route::group(['middleware' => 'admin'], function () 
{ 
    Route::get('/home', 'HomeController@index')->name('home');
});

public function __construct()
{ 
    $this->middleware('admin');  
}

【问题讨论】:

  • 转储$this-&gt;roles

标签: php laravel permissions admin middleware


【解决方案1】:

模型上的roles() 关系是多对多关系,因此调用$this-&gt;roles 返回模型集合,而不是单个模型实例。如果您想检查 Admin 是否是当前用户拥有的角色之一,请尝试以下操作:

public function isAdmin()
{
    if ($this->roles->pluck('name')->contains('Admin')) {
        return true;
    }
    return false;
}

pluck() 方法将您的集合(在本例中为名称字段)中的数据“列”作为新集合返回。 contains() 方法在集合中搜索给定值,如果集合包含该值,则返回 true,否则返回 false。

https://laravel.com/docs/5.7/collections#available-methods

【讨论】:

    【解决方案2】:

    $this-&gt;roles 返回一个Collection 实例。因此您无法从集合中访问属性。那是错误。

    在这种情况下,您只需要知道该用户是否是管理员。因此,您不必获取所有角色来执行此操作。而且这样做的效率也较低。

    所以最好的解决方案是使用exists()函数。

    public function isAdmin()
    {
        // is there a role which name is admin.
        if ($this->roles()->where('name', 'Admin')->exists()) {
            return true;
        }
        return false;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-20
      • 1970-01-01
      • 2014-12-13
      • 2014-04-18
      • 1970-01-01
      • 2012-06-26
      • 1970-01-01
      • 2023-03-31
      相关资源
      最近更新 更多