Say I have a custom logic for validating the uniqueness of a FormRequest field, something requiring to find another resource in the database like below:
class CreateMyResourceRequest extends FormRequest {
public function rules() {
return [
'my_field' => [
Rule::unique('some_other_resource', 'some_column')
->where(function ($query) {
$otherResource = SomeOtherResource::where(...)->firstOrFail();
// Process the retrieved resource
}),
]
The firstOrFail() call obviously makes the request fail with a 404 - Not found while I would like to return a 422 with a validation error on the field.
Is there a way to achieve this while still using the Rule::unique() provided by the framework?
Thanks in advance!
Rule::unique()is already sending validation error response, what are you trying to achieve?firstOrFail()method as I need to know that the referenced resource actually exists.. but that gives back a 404 rather than a validation error..