Search code examples
validationlaravelunique

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?


Solution

  • 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 .