When creating a new Role
an administrator can select different rights he'd like to assign to that role. After saving the freshly created Role
to the database, the selected rights are sync'd to the right_role
table.
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');
}
But how do I validate the submitted rights against not existing values? Can I do this within my CreateRoleRequest
?
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',
];
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments