I would like to add custom validations rules on my Laravel Controller:
- The container exists in the database
- The logged user is owner of the resource
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?
idof the resource and the rule does not apply to any value in therequest...$idof my resource, so I cannot check if it exists :(