I would like to add custom validations rules on my Laravel Controller:
So I wrote this:
public function update($id, Request $request) {
$validator = Validator::make($request->all(), [
'name' => 'required|unique:stock.containers|max:255'
]);
$container = Container::find($id);
if(!$container)
{
$validator->errors()->add('id', 'Not a valid resource');
}
if($container->owner_id != user_id())
{
$validator->errors()->add('owner_id', 'Not owner of this resource');
}
if ($validator->fails()) {
return response()->json($validator->errors(), 422); //i'm not getting any
}
}
Unfortunately the $validator->errors()
or even $validator->addMessageBag()
does not work. I noticed $validator->fails()
clears the error messages and adding an error will not make the validation to fail.
What is the proper way to achieve this?
Then you can use after
:
public function update($id, Request $request) {
$validator = Validator::make($request->all(), [
'name' => 'required|unique:stock.containers|max:255'
]);
$validator->after(function($validator) use($id) {
$container = Container::find($id);
if(!$container)
{
$validator->errors()->add('id', 'Not a valid resource');
}
if($container->owner_id != user_id())
{
$validator->errors()->add('owner_id', 'Not owner of this resource');
}
});
if ($validator->fails()) {
return response()->json($validator->errors(), 422); //i'm not getting any
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.