Laravel Unique Validation with Condition Example

Admin   Laravel   685  2021-03-15 10:20:04

Hello Friends,

In this blog, I would like share you how to use unique validation with condition in laravel application. I need to validate if the email field on the users table is unique only if the deleted column is not 1 in laravel app.

In this article, We will use unique validation with condition in laravel. laravel unique validation with condition using rule.

You have to include the Rule class with a use at the top of your file after the namespace declaration.

 

use Illuminate\Validation\Rule;

Here I will give solution for laravel unique with condition. So Let's see the solution and implete in your laravel project.

Solution :

 

use Illuminate\Validation\Rule;

public function index()

{

$request->validate([

'name' => 'required',

'email' => [

'required','email',Rule::unique('transporters')->where(function($query) {

$query->where('deleted', '=', '0');

})

],

])

}

Solution : 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);

})

],

])

}

It will help you...