phplaravellaravel-8laravel-formrequest

Laravel: make validation rule fail when using closure


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!


Solution

  • I'd suggest the following

    public function rules()
    {
        return [
            "your_field" => ["you_can_have_more_validations_here", function($key, $value, $cb) {
    
                $queryResult = SomeModel::find(1);
    
                if (someCondition) {
                    $cb("your fail message");
                }
            }]
        ];
    }
    

    when the $cb run the validation will fail with 422