Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel 4: validation unique (database) multiple where clauses

The laravel 4 documentation mentions unique field validation. They explain here how to include where clauses to the unique validation. A single WHERE clause for the unique table for example:

$validator = Validator::make(
    array(
        'name' => 'John Doe'
    ),
    array(
        'name' => 'unique:table,field,NULL,id,field1,value1'
    )
);
  • http://laravel.com/docs/validation#rule-unique

Now i assume this does something like:

"SELECT id FROM table WHERE field = 'John Doe' AND field1 = value1 LIMIT 1"

Then check's if this query returns a result and if not passes the validator.

So i was wondering if there was a way to add more where clauses? And if so how?

like image 844
rofavadeka Avatar asked Oct 15 '13 08:10

rofavadeka


1 Answers

Ending of my original question:

Can i just stack them or how do i have to write my validation if not? So can i just add ",field2,value2,field3,value3" ect. and stack them like this?

Answer

Yes i can just stack them like below. So if i would like to add multiple where clauses to my unique validator i would do it like this:

'name' => 'unique:table,field,NULL,id,field1,value1,field2,value2,field3,value3'


Exceptions

The third parameter given in the unique rule is the except parameter, according to the Laravel documentation.

unique:table,column,except,idColumn

I left this parameter NULL because it is not that relevant to the original question. For those who would like to know what the function of this NULL is within the unique rule, let me elaborate:

The except parameter forces a unique rule to ignore a given ID. So specifying it as a NULL will result in checking against every record ( i.e. ignoring nothing ).

For example: Let's say we want our user email to be unique but our admin user might also have a normal user account with the same email. Assuming our admin user is the first user we created it has the id of 1. So what we could do when creating new users is:

'name' => 'unique:users,email,1,id'
like image 187
rofavadeka Avatar answered Sep 16 '22 19:09

rofavadeka