Laravel 停止根据用户角色更新模态属性

Laravel stop modal attribute being updated based on user role

我正在创建一个系统,其中有用户,并且用户有很多用户角色。用户角色还包含权限。某些字段受到保护,因此如果用户没有特定权限,就无法覆盖它们。

例如,用户可能具有属性 "email",除非该用户具有 "update-email-address".

权限,否则用户无法更改该属性

我最初打算将这个概念实现为特征或抽象 class,但我想不出一种不涉及重载 Eloquent 模型构造函数的方法方法,或者完全重载另一个方法。

我希望做的是能够在如下模型中指定一个数组,并通过使用区域或扩展以某种方式阻止更新模型属性:

/**
 * The attributes that should only be updatable by given user with the 
 * specified permission
 *
 */    
public $update_only_by_permission = [
    'email'          => ['update-email-address'], 
];

有办法实现吗?

我偶然发现了一种为扩展模型的特征提供启动方法的方法,并且能够通过以下方式实现:

许多 Eloquent 模型使用的特性:

use Auth;
trait AttributeVisibleByPermissionTrait {

    /**
    *   Stops updating of the object attributes if the authenticated 
    *   user does not have the given permission provided in the 
    *   $object->update_only_by_permission array.
    */
    public static function bootAttributeVisibleByPermissionTrait(){

        static::updating(function($object){ 
            foreach ($object->update_only_by_permission as $attribute => $permissions) {
                foreach ($permissions as $permission) {
                    if(!Auth::User()->can($permission)) {
                        unset($object->$attribute);
                    }
                }
            }
        });

    }
}

用户模型:

class User extends Authenticatable
{
    use AttributeVisibleByPermissionTrait;
    /**
     * The attributes that should only be updated by given user auth permissions
     *
     * @var array
     */    
    public $update_only_by_permission = [
        'email'              => ['update-email-address'], 
    ];
}