Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel form validation unique using 2 fields

Tags:

php

laravel-5

How can I have a unique validation rule on 2 fields?

a. The application should not allow two people to have the same identical first name and last name.

It is allowed that the users fills in only a first name or only a last name. Because the user may have only one of them.

b. But if the user enters only a first name (Glen), no other person in the table should have the same (first name = 'Glen' and last name = null). another 'Glen Smith' ok.

I tried the following rule. It works great when both fields (first and last name) are not null:

'firstName' => 'unique:people,firstName,NULL,id,lastName,' . $request->lastName

This rule fails on b. when only one field is present.

Any hint?

like image 885
Warrio Avatar asked Feb 08 '17 14:02

Warrio


2 Answers

The built in unique validator wouldn't really support what you're trying to do. It's purpose is to ensure that a single valid is unique in the database, rather than a composite of two values. However, you can create a custom validator:

Validator::extend('uniqueFirstAndLastName', function ($attribute, $value, $parameters, $validator) {
    $count = DB::table('people')->where('firstName', $value)
                                ->where('lastName', $parameters[0])
                                ->count();

    return $count === 0;
});

You could then access this new rule with:

'firstName' => "uniqueFirstAndLastName:{$request->lastName}"

You'll probably find you might need to tweak your database query a little bit as it's untested.

like image 114
edcs Avatar answered Nov 09 '22 10:11

edcs


I think you are looking for something like that:

 'unique:table_name,column1,null,null,column2,'.$request->column2.',column3,check3'
like image 8
Nur Uddin Avatar answered Nov 09 '22 10:11

Nur Uddin