Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 multiple table unique validation

For example, I have 2 tables : sites1 and sites2

I need to check that field url which is comes from my html form is unique.

Here my validation rule :

public function rules()
    {
        return [
            'url' => unique:sites1|unique:sites2'
        ];
    }

Unfortunately, this rule applies only for sites2 table. Is there any possible ways to validate both tables?

like image 278
Nitromoon Avatar asked Feb 19 '16 09:02

Nitromoon


2 Answers

Your validation rule seems ok. Just make sure that both sites1 and sites2 table has field name url and both in same database.

Your unique:sites1 rule will be translated into SQL

select count(*) as aggregate from `sites1` where `url` = ?

While unique:sites2 rule will be translated into SQL

select count(*) as aggregate from `sites2` where `url` = ?

See if first SQL does return result. Long URL may result non unique if used with limited index length. It may be better if you could store hash value of URL so you can compare url just by using hash.

like image 87
Zamrony P. Juhara Avatar answered Nov 04 '22 20:11

Zamrony P. Juhara


No need to maintain the same name in two different tables

In laravel 4.2

Validator::make(Input::all, [
    'url' => 'unique:site1,your_column_name|unique:site2:your_column_name_2'
]);

Laravel 5.*:

$this->validate($request,[
    'url' => 'unique:site1,your_column_name|unique:site2:your_column_name_2'
]);

Hopefully it's working fine.

like image 9
Nadimuthu Sarangapani Avatar answered Nov 04 '22 20:11

Nadimuthu Sarangapani