pandishpan / authorized-attributes
Laravel 模型策略授权的模型属性
dev-master
2023-06-22 15:44 UTC
Requires
- illuminate/auth: 9.*
- illuminate/support: 9.*
Requires (Dev)
- orchestra/testbench: 7.*
This package is not auto-updated.
Last update: 2024-09-27 19:47:42 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); } }