Robinvm
Robinvm

Reputation: 47

Laravel - Exclude the row from the logged in user when validating unique

How can i exclude the row from the logged in user when validating something that must be unique (except the row from the user itself)?

Thanks in advance!

Upvotes: 1

Views: 512

Answers (2)

Saumya Rastogi
Saumya Rastogi

Reputation: 13703

You can pass the logged in user's id in validation rule - unique like this:

$validator = Validator::make($request->all(), [
    'email' => 'unique:users,email,' . auth()->id,
]);
// This will validate unique email in users table except the column referenced to the logged in user id.

unique:table_name,column_name,except,idColumn

See more about unique rule

Hope this helps!

Upvotes: 1

Alexey Mezenin
Alexey Mezenin

Reputation: 163788

Your question is not very clear. If you are talking about something like user profile update (when user has to have unique email, but his email is already in DB) you should read this from the docs:

Sometimes, you may wish to ignore a given ID during the unique check. For example, consider an "update profile" screen that includes the user's name, e-mail address, and location. Of course, you will want to verify that the e-mail address is unique. However, if the user only changes the name field and not the e-mail field, you do not want a validation error to be thrown because the user is already the owner of the e-mail address.

To instruct the validator to ignore the user's ID, we'll use the Rule class to fluently define the rule. In this example, we'll also specify the validation rules as an array instead of using the | character to delimit the rules:

use Illuminate\Validation\Rule;

Validator::make($data, [
    'email' => [
        'required',
        Rule::unique('users')->ignore($user->id),
    ],
]);

Upvotes: 2

Related Questions