relaxsd / laravel-model-gates

Laravel模型权限

0.1.0 2020-12-14 14:26 UTC

This package is auto-updated.

Last update: 2024-09-14 23:09:03 UTC


README

此包允许授权访问模型属性,因此通过使用Laravel Gates和策略,您可以基于授权减少返回的数据。

安装

使用Composer引入此包。

{
    "require": {
        "relaxsd/laravel-model-gates": "0.1.*"
    }
}

用法

这是一个模型权限的示例。

use Relaxsd\Gate\ModelGate;

class ProjectGate extends ModelGate {

    public function members()
    {
        if (\Gate::allows('indexForProject', [\App\Member::class, $this->entity])) {
            return $this->entity->members;
        }
        return new \Illuminate\Database\Eloquent\Collection(); // Not authorized: return an empty collection instead. 
    }

}

接下来,在你的实体中引入Relaxsd\Gate\ModelGateTrait特性,这将自动实例化你的模型权限类。

这是一个示例——可能是一个Laravel的User模型。

<?php

use Relaxsd\Gate\ModelGateTrait;

class Project extends \Eloquent {

    use ModelGateTrait;

    protected $gate = 'ProjectGate';

}

就这样!你已经完成了。现在,在你的代码中,你可以做

    return $project->gate()->members; // Only the members we're allowed to see

注意,调用gate()方法(它将返回你的新或缓存的模型权限对象)还提供了这样一个好处,即清楚地指出了你需要修改实现的地方。

祝您玩得开心!