Home > other >  Laravel: make validation rule fail when using closure
Laravel: make validation rule fail when using closure

Time:02-20

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 retireved 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!

CodePudding user response:

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

CodePudding user response:

Don't use firstOrFail, instead just use first and check if the output is null. If it is, return false.

Alternatively, the more Laravel way of doing it is:

$query->leftJoin('otherresource', 'primarykey', 'foreignkey')->where(...)
  • Related