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

时间:2017-03-08 14:14:58

标签: php laravel laravel-5.3

我创建了一个有用户的系统,用户有很多用户角色。用户角色还包含权限。某些字段受到保护,因此如果用户没有特定权限,则无法覆盖这些字段。

例如,用户可能具有属性" email"用户无法更改,除非用户拥有权限" update-email-address"。

我原本打算将这个概念作为特征或抽象类来实现,但是我无法想出这样做的方法,它不会涉及重载Eloquent Model构造函数方法,或者完全重载另一种方法。

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

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

有没有办法实现这个目标?

1 个答案:

答案 0 :(得分:1)

我偶然发现了为扩展模型的特征提供引导方法的方法,并且能够通过以下方式实现此目的:

许多雄辩模特使用的特质:

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'], 
    ];
}