general666
general666

Reputation: 1039

Laravel validation with custom condition

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?

Upvotes: 0

Views: 3106

Answers (2)

Soubhagya Kumar Barik
Soubhagya Kumar Barik

Reputation: 2595

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!');
        }
    });

Upvotes: 0

Andrej
Andrej

Reputation: 7504

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 .

Upvotes: 1

Related Questions