unique_validation

How to use Laravel Unique Validation with Condition Example

Hello Nerd, In this post, I’d like to demonstrate how to use Laravel unique validation with condition. In the laravel app, I need to validate if the email field on the users table is unique only if the deleted column is not 1.
In this article, we will use laravel’s unique validation with condition. Laravel unique validation with conditional logic via rule.
After the namespace declaration, you must include the Rule class with a use at the top of your file.

use Illuminate\Validation\Rule; 

I will provide a solution for laravel unique with condition here. So, let’s look at the solution and how to implement it in your Laravel project.

Example 1: Initial

...
use Illuminate\Validation\Rule; 

public function index()
{
	$request->validate([
    		'name' => 'required',
            'email' => [
                'required','email',Rule::unique('transporters')->where(function($query) {
                  $query->where('deleted', '=', '0');
              })
            ],
        ])
}
...

Example 2: On Update

...
use Illuminate\Validation\Rule; 

public function index()
{
	$request->validate([
    		'name' => 'required',
            'email' => [
                'required','email',Rule::unique('transporters')->where(function($query) {
                  $query->where('deleted', '=', '0')
                  ->where('id', '!=', $id);
              })
            ],
        ])
}
...

Leave a Reply