创建新的Role
时,管理员可以选择他想要分配给该角色的不同权限。将新创建的Role
保存到数据库后,所选权限将同步到right_role
表。
public function store(CreateRoleRequest $request) {
$role = new Role(['name' => $request->get('name')]);
$rights = [];
foreach ($request->get('rights') as $id => $enabled) {
if ($enabled) {
$rights[] = $id;
}
}
$role->save();
$role->rights()->sync($rights);
return redirect()->route('users.index');
}
但是,如何针对不存在的值验证提交的权限?我可以在CreateRoleRequest
吗?
答案 0 :(得分:2)
This can be done with custom validator. Here is example how the custom validators can be used in CreateRoleRequest
public function __construct() {
Validator::extend("valid_rights", function($attribute, $value, $parameters) {
$rules = [
'right_id' => 'exists:rights,id'
];
foreach ($value as $rightId) {
$data = [
'right_id' => $rightId
];
$validator = Validator::make($data, $rules);
if ($validator->fails()) {
return false;
}
}
return true;
});
}
public function rules() {
return [
'containers' => 'required|valid_rights',
];
}