salomoni/authorized-attributes

此包已被弃用,不再维护。作者建议使用 vantage/authorized-attributes 包。

Laravel授权模型属性

v5.0.0 2019-11-10 15:13 UTC

README

提供动态添加 $hidden$fillable 列到模型的能力。

如果需要,请参阅 Laravel API 资源

安装

将包要求添加到Laravel项目。

composer require vantage/authorized-attributes

使用

请注意,此包回退到核心 Guard,并且在Laravel版本之间编写策略时有一些细微的差异。请参阅官方文档 https://laravel.net.cn/docs/authorization

使用 Vantage\AuthorizedAttributes 特性

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Vantage\AuthorizedAttributes;

class Post extends Model
{
    use AuthorizedAttributes;

    /**
     * The attributes that should be fillable from requests.
     *
     * @var array
     */
    protected $fillable = ['title', 'content', 'author_id'];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array
     */
    protected $hidden = ['draft'];
}

创建和注册模型策略.

<?php

namespace App\Policies;

use App\Post;
use App\User;

class PostPolicy
{
    /**
     * Determine if an draft attribute can be seen by the user.
     *
     * @param  \App\User  $user
     * @param  \App\Post  $post
     * @return bool
     */
    public function seeDraft(User $user, Post $post)
    {
    	// Post drafts can only be seen by admins and the post author
        return $user->isAdmin() || $user->created($post);
    }

    /**
     * Determine if the author_id attribute can be changed by the user.
     *
     * @param  \App\User  $user
     * @param  \App\Post  $post
     * @return bool
     */
    public function editAuthorId(User $user, Post $post)
    {
    	// Admins can re-assign the author for non-published posts
        return $user->isAdmin() && $post->isNotPublished();
    }
}

自定义

与始终隐藏属性混合使用

如果没有找到策略或能力,属性将按照常规隐藏。

修改能力方法名称

<?php

use Illuminate\Support\Str;

class Post extends Model
{
    /**
     * Get the method name for the attribute visibility ability in the model policy.
     *
     * @param  string  $attribute
     * @return string
     */
    public function getAttributeViewAbilityMethod($attribute)
    {
        return 'see'.Str::studly($attribute);
    }

    /**
     * Get the model policy ability method name to update an model attribute.
     *
     * @param  string  $attribute
     * @return string
     */
    public function getAttributeUpdateAbilityMethod($attribute)
    {
        return 'edit'.Str::studly($attribute);
    }
}