vantage / authorized-attributes
Laravel 的授权模型属性
v5.0.0
2019-11-10 15:13 UTC
Requires
- illuminate/auth: 6.x
- illuminate/support: 6.x
Requires (Dev)
- orchestra/testbench: 4.x
This package is auto-updated.
Last update: 2024-08-30 01:38:10 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); } }