Validate composite key with Laravel?

2

I have a table where the employees of a company with the following fields are inserted; id , name , email , use_id , role_id .

  

user_id is the id of the company that the official works.

The validation that I need to do is verify that email is already linked to empresa , since this official can be registered for other companies but never 2x for the same company, in summary an email can be registered more than 1x as long as it is not for the same user_id (company)

Following the documentation I added the following rule:

return [
    'name' => 'required|string',
    'email' => 'required|email|max:255|'.Rule::unique('employees')->where(function($query){
           $query->where('user_id', Auth::user()->id);
        }),
    'password' => 'required|min:6|confirmed',
    'role_id' => 'integer'
];

But validation never applies and to the verification; where email = 'x' AND user_id = 'y'

Example:

The following records are valid:

| id | user_id |  email     |
|--------------|:----------:|
| 1  |    4    | [email protected] |
| 2  |    5    | [email protected] |

The following is invalid :

| id | user_id |  email     |
|--------------|:----------:|
| 1  |    4    | [email protected] |
| 2  |    4    | [email protected] |

In the first example the same email is used with user_id different then the insertion / validation is valid, in the second example it is invalid because the user_id is already linked to the email '[email protected]' p>

A good example is a SASS of e-commerce, where several clients can belong to several stores (which will be on the same table)

    
asked by anonymous 25.08.2017 / 17:55

1 answer

4

Try this:

return [
    'name' => 'required|string',
    'email' => ['required','email','max:255', Rule::unique('employees')
         ->where(function($query) { $query->where('user_id', Auth::user()->id); })
    ],
    'password' => 'required|min:6|confirmed',
    'role_id' => 'integer'
];

What were the differences?

Instead of the dot it was a comma, and the validation in this case is a% w as% described in the documentation.

Reference

25.08.2017 / 19:56