laravel 4: validation unique (database) multiple w

2019-02-13 17:56发布

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'
    )
);

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?

1条回答
唯我独甜
2楼-- · 2019-02-13 18:41

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'
查看更多
登录 后发表回答