Usually Laravel's form request returns a generic 400 code on failing validation like this:
{
"message": "The given data is invalid",
"errors": {
"person_id": [
"A person with ID c6b853ec-b53e-4c35-b633-3b1c2f27869c does not exist"
]
}
}
I'd like to return a 404 if a request does not pass my custom rule.
My custom rule checks if a record exists in the DB:
class ValidatePersonExists implements Rule
{
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
public function passes($attribute, $value)
{
return Person::where('id', $value)->exists();
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return "A person with ID :input does not exist";
}
}
If I throw a ModelNotFoundException on failure of the exists() check, where can I catch it to respond with a friendly 404 response?
Here's my form request where I am using the rule:
public function rules()
{
return [
'person_id' => ['bail', 'required', 'uuid', new ValidatePersonExists],
];
}