0

I'm trying to setup validation rule with condition but have no idea how to do following:

In my form I have title_url (array for multiple language versions). I want to have unique title_url but only when module_cat_id in the form has same value as existing rows in DB.

This is my rule:

'title_url.*'   => 'required|min:3|unique:modules_cat_lang,title_url'

Any ideas how to solve this?

2 Answers 2

1

You can define your custom similar to code below:

\Validator::extend('custom_validator', function ($attribute, $value, $parameters) {
        foreach ($value as $v) {
            $query = \DB::table('modules_cat_lang') // use model if you have
                ->where('title_url', $v)
                ->where('module_cat_id', \Input::get('module_cat_id'));
            if ($query->exists()) {
                return false;
            }
        }
    });
'title_url.*'   => 'required|min:3|custom_validator'

Read more here https://laravel.com/docs/5.3/validation#custom-validation-rules .

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

Comments

0

If you want to add your own custom validation logic to the existing laravel validator then You can use after hooks. Please have a look at the below examples.

Reference : https://laravel.com/docs/8.x/validation#adding-after-hooks-to-form-requests

Example 1(Without Parameter)

    $validator->after(function ($validator)  {
        if ('your condition') {
            $validator->errors()->add('field', 'Something went wrong!');
        }
    });

Example 2(With Parameter) // Here you can pass a custom parameter($input)

    $validator->after(function ($validator) use ($input)  {
        if ($input) {
            $validator->errors()->add('field', 'Something went wrong!');
        }
    });

1 Comment

How do I add these customs in Request Class, if I set normal default rules in Custom Request class?

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.