0

I want to verify if email address in my database is duplicate or not? Here is my codes :

'users.*.email'=> ['required','unique:users','email']

and this is my Controller

UsersController

public function MassStore(MassStoreUserRequest $request)
{

    $inputs = $request->get('users');
    return redirect()->route('admin.users.index');
}

and this is my POST data (post data($inputs) will send like as below) :

'users' => [
    [
        'name' => 'Ken Tse',
        'email' => '[email protected]',
        'password' => 'ken12ken34ken',
    ],
    [
        'name' => 'Ken Tse',
        'email' => '[email protected]',   //duplicate, so need trigger error
        'password' => 'ken12ken34ken',
    ],
]

and this is error I get :

[2019-12-10 15:51:16] local.DEBUG: PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '[email protected]' for key 'users_email_unique'

MassStoreUserRequest

public function rules()
{
    return [
        'users'                => ['required','array'],
        'users.*.name'         => ['required'],
        'users.*.email'        => ['required','unique:users','email'],
        'users.*.password'     => ['required','min:8']
    ];
}

3 Answers 3

3

To prevent duplicate data being submitted in an array you can use the distinct rule:

return [
    'users'            => ['required', 'array'],
    'users.*.name'     => ['required'],
    'users.*.email'    => ['required', 'email', 'distinct', 'unique:users'],
    'users.*.password' => ['required', 'min:8'],
];
Sign up to request clarification or add additional context in comments.

Comments

1

Please try to use like this:

$rules = array(
            "name" => "required",
            "email" => "required|email|unique:users",
             "password" => "required|min:6",

        );

Comments

0

Just use the distinct with your email keyword such as :

public function rules()
{
    return [
        'users'                => ['required','array'],
        'users.*.name'         => ['required'],
        'users.*.email'        => ['required','unique:users','email', 'distinct'],
        'users.*.password'     => ['required','min:8']
    ];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.