Timothy
Timothy

Reputation: 4285

How to write Laravel validation for unique fields

I cannot seem to find an exhaustive guide on how to validate unique fields in Laravel. Kindly elaborate what the difference could be between the following validation rules and which one is wrong or redundant.

1

$rules = ['email' => 'email|unique:users']

2

$rules = ['email' => 'email|unique:users,email']

3

$rules = ['email' => "email|unique:users,email,{$user->email}"]

4

$rules = ['email' => "email|unique:users,email,{$user->email},email"]

Upvotes: 0

Views: 299

Answers (1)

user1669496
user1669496

Reputation: 33058

The first one is simply looking in the users table to make sure the email is unique. Because you didn't supply a column as the second argument, it's going to assume the column name is the same as the key, in this case email.

The second one is simply declaring which column should be checked for the email column. In this case, it's not required because the email column is email which Laravel already assumes. If your email column in the database was named something like user_email, then you'd have to pass in user_email to the validator so it knows which column to check for the email address.

The third one, you should be passing an id of the user with that email. This will tell Laravel that the email should be unique unless that email happens to be set for that id. This is useful for edit forms. If you are editing a user who has the email [email protected] and you try to save it, having a unique validator won't allow that form to save because it already sees [email protected] in the table (the one you are trying to edit). So this way, you pass that user's id in and validation will pass.

The fourth one, you are simply declaring the name of the primary id column. The vast majority of the time, this is not required as Laravel just assumes the primary key column is called id. If for some reason your primary key on your users table is user_id, then you would pass in user_id so it knows which column to match the id on.

Upvotes: 3

Related Questions