How to use “unique” validation in Laravel for create and update model

How to use "unique" validation in Laravel for create and update model

In this article let us understand how to use “unique” validation in Laravel for create and update model.

In Laravel unique validation is used to have a column with non-repeating values throughout, basically avoid duplicates.

Let’s say we have email field on users table and we use it to sign-in the user. In this case obviously we will need unique email address only for every user. If we will be using phone number for login, we need phone as unique column.

On model when we use unique validation we will need to use it for different methods as while creating and while updating.

Lets understand both of them:

1) unique – on create

When we use unique while create it becomes simple that we check from all existing values and give error if we find any match. Lets check how to use it in code :

use Illuminate\Http\Request;
public function store(Request $request)
{
    $validatedData = $request->validate([
        'email' => 'required|email|unique:users|max:255'
    ]);
    // Process the validated data
}

As you can see from above we use validate() method where we will define separate rules for each of our request fields.

  • unique:users: The email field must be unique in the “users” table.

Here we are checking email field from users table must be unique. That’s it.

2) unique – on update

unique validation on update becomes little tricky as we already have that email in our table.

Lets say we are having one record with “test@example.com” and we have functionality to update the email in our project. So, when user will try to validate using unique it will find that record and give error, but ideally we are targeting that record only to update which will not create duplicate.

Here, Laravel provides a way to do that by passing existing id so validator will skip that record and let us update.

Let’s understand using below syntax :

use Illuminate\Http\Request;
public function update(Request $request, $id)
{
    $validatedData = $request->validate([
        'email' => 'required|email|unique:users,email,'.$id
    ]);
    // Process the validated data
}

$id – as targeted tables primary id on which record will be processed.

So, by this means we will skip the record with given id on users table for unique email column.

That’s all on how to use “unique” validation in Laravel for create and update model. Hope this finds you helpful.

See other articles on Laravel here.