Validate composite key with Laravel?

Asked

Viewed 557 times

3

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

user_id is the id of the company the employee works for.

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

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

However, the validation never applies the and for the verification; where email = 'x' AND user_id = 'y'

Example:

The following records below 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 then the insertion/validation is valid, in the second example is invalid because the user_id already linked to the email `[email protected]"

A good example is a SASS e-commerce, where several customers may belong to several stores (which will be in the same table)

  • Actually the e-mail cannot repeat correct?

  • Yes, it can be repeated since the column user_id do not repeat for the same email, this is the composite key principle

  • Then there is something strange ... well still the answer below I did about the error when writing the rule, take a look

  • @Virgilionovic put some examples to facilitate understanding.

  • Dear Rafael, OK, I see problems in that, but, it’s my concept, now I’d like to know if the answer worked, because, you asked that?

1 answer

5


Try it like 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 point it was a comma and the validation in this case is a array as described in the documentation.

Reference

  • the validation does not accept arrays as a value; Method [validateRequired|email|max] does not exist.

  • @Rafaelacioly, is an array, take a look at the edition, passed to me unnoticed ...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.