Laravel 7 Unique Validation Example Tutorial
Laravel 01-Mar-2021

Laravel 7 Unique Validation Example Tutorial

In this laravel unique validation example tutorial, you will learn how to use unique validation and rules with insert, update data in laravel.

First of all, you check if this data exists or not in database tables in laravel before insert or update data into database tables. So at that time, you need to add unique validation for database table columns.

The laravel unique validation stop duplicate entry. It means, when you insert data into datbase table, it check if exist or not in database table. If data exist, it return message “the column name value is already exist”. Otherwise it insert new entry into database table.

And you can also except some columns of your database with laravel validation unique except.

Laravel Unique Validation Example

Here, you will learn the following step by step about laravel uniqu valiation:

  • Simple Unique Validation on Controller
  • Unique Validation with Column Name
  • Unique Validation with Rule
  • Laravel Unique Validation on Update

1: Simple Unique Validation on Controller

When you insert data into database table. But first of all, you need to check data is exist or not. So you can use simple unique validation in laravel.

The following unique validation rule is simple. And you can use it as follow:

public function store(Request $request)
{
       request()->validate([
 
        'name' => 'required',
        'username' => 'required|min:8',
        'email' => 'required|email|unique:users',
        'contact' => 'required|unique:users'
 
       ]);
}

2: Unique Validation with Column Name

The following unique validation rules with column name on controller methods, you can use as follow:

public function store(Request $request)
{
 
       request()->validate([
 
        'name' => 'required',
        'username' => 'required|min:8',
        'email' => 'required|email|unique:users,email',
        'contact' => 'required|unique:users'
 
       ]);
}

3: Unique Validation with Rule

Before using unique validation with the rule, you need to import use Illuminate\Validation\Rule;. Then you can use it as follow:

public function store(Request $request)
{
       request()->validate([
        'name' => 'required',
        'username' => 'required|min:8',
        'email' => ['required', Rule::unique('users')],
        'contact' => 'required|unique:users'
       ]);
}

4: Laravel Unique Validation on Update

Sometimes, you update data in the database table with unique validation. You can use it as follow:

public function store(Request $request)
{
       request()->validate([
        'name' => 'required',
        'username' => 'required|min:8',
        'email' => 'required|email|unique:users,email,'.$this->user->id,
        'contact' => 'required|unique:users'
       ]);
}

Conclusion

In this laravel unique validation example tutorial, you have learned how to use unique validation in laravel apps.