Home » Php » php – Laravel 5 multiple table unique validation

php – Laravel 5 multiple table unique validation

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&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.

Answer:

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.

Answer:

In the above answer i think you can’t use custom error message, you can do in another way just copy the filed in another field for the two checks.

 public function validator(array $data)
    {
        $data = ['url2' => $data['email']];

        $rules = [
            'url' => 'unique:sites1',
            'url2' => 'unique:sites2',
        ];

        $messages = [
            'url.unique' => 'url unique in site 1',
            'url2.unique' => 'url unique in site 2',
        ];

        return $validator = Validator::make($data, $rules, $messages);
    }





  if ($validator->fails()) {
                if(!empty($validator->errors()->get('url2'))) {
                    $validator->errors()->add("url", 'url unique in site 2');
                }
   }