How to prevent email insertion if it already exists with a specific id in laravel?

I have a table in which I am trying to store email addresses. These email addresses will be saved using user_id .

For example, in the email_list table

 |ID | user_id | email | ............................... | 1 | 101 | john@gmail.com | ............................... | 2 | 102 | john@gmail.com | 

In the table above, you can see that the same email addresses are stored with different user_id , which is what I'm trying to do.

I am currently trying to do a simple laravel check as follows.

 'email' => 'required|unique:email_list|email', 

So, is there a way to check for existing email addresses if the string has the same user_id ? I am using laravel 5.2. I would appreciate if someone leads me. Thanks you

Edited after 3 hours

I also add the same question on github as issue . The person says that I need to create my own validation rule.

+3
php laravel laravel-5 laravel-validation
Sep 20 '16 at 10:21
source share
2 answers

Forcing a unique rule to ignore a given identifier

You can specify an identifier that will be ignored as an additional third parameter. In addition, if your table uses a primary key column name other than id, you can specify it as an optional fourth parameter

 'email' => "unique:{$table},{$field},{$user->id},{$idField}" 

So in your case it will be as follows

 'email' => "unique:email_list,email,{$user->id},user_id' 
+1
Sep 20 '16 at 10:52
source share

This is against the existing rule.
First of all, checking an existing rule is based on the condition that the fields are used or not.
I think if we used this as the opposite, it would be useful for you.

Example: -

  'email' => 'exists:email_list,email,user_id,!102' 

i.e.,

  'email' => 'exists:email_list,email,user_id,!'. $user_id 

otherwise

  'email' => 'exists:email_list,email,user_id,!'. Input::get(user_id) 

when using input and import

  use Illuminate\Support\Facades\Input; 

and change the contents of the message
Please try these answers and answer what happened .. or does it work for you ..?

0
Sep 21 '16 at 12:45
source share



All Articles