0

I have laravel validation request form, like this:

public function rules()
{
    $id = $this->input('wlId');

    return [
        'id'          => ['sometimes ', 'integer'],
        'domain_name'   => ['required', 'string', 'unique:white_label,domain_name' . $id],
        'disabled'      => ['required', 'boolean']
    ];
}

I set id for ignore my entry during the unique check, but if id is't an integer but for example a string then I will get sql error from validator.

How can I stop validation if the id field fails validation?

1
  • because you specified that should be integer: 'id' => ['sometimes ', 'integer'], That means that should be only integer, but if you want to be an integer you should use 'numeric' Commented Oct 30, 2020 at 16:37

2 Answers 2

1

You are going to ignore a certain value while using unique validation rule. Consider the following snippet;

use Illuminate\Validation\Rule;

// ...

public function rules() {
    $id = $this->input('wlId');

    return [
        'id' => ['sometimes ', 'integer'],
        'domain_name' => [
            'required',
            'string',
            Rule::unique('white_label', 'domain_name')->ignore($id)
        ],
        'disabled' => ['required', 'boolean']
    ];
}

For more details, see this link; https://laravel.com/docs/8.x/validation#rule-unique

Sign up to request clarification or add additional context in comments.

1 Comment

It's the same like in my example. If no id field is passed you will get sql error. Since the validator will try to get the domain name from the white_label table by the id
0

As mentioned in the documentation you can use bail rule

Sometimes you may wish to stop running validation rules on an attribute after the first validation failure. To do so, assign the bail rule to the attribute

    $request->validate([
    'title' => 'bail|required|unique:posts|max:255',
    'body' => 'required',
    ]);

In this example, if the unique rule on the title attribute fails, the max rule will not be checked. Rules will be validated in the order they are assigned.

1 Comment

Bail to stop my validation of a certain field, but further validation will still go. In your example. If the title field is not passed, then unique: posts will no longer be validated, but the body field will still be validated. I want the body field not to be validated in case of a failed title field validation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.