In this tutorial you will learn about the Laravel 7 Unique Validation Example Tutorial and its application with practical example.
In this Laravel 7 Unique Validation Example Tutorial I’ll show you how to implement unique validations in laravel. In this tutorial you will learn add unique validation in laravel fields. In this step by step tutorial I’ll demonstrate various example to implement unique validation in laravel.
Laravel 7 Unique Validation Example Tutorial
- 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
In laravel when you insert data into table but you want 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
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
In laravel it is possible to pass column name along with the unique validation. Please have look in below example code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
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
In this example we have demonstrate to implement unique validation on update operation in laravel.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
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' ]); } |