Laravel unique validation with record active condition

Laravel provides a good validation functionality we can easily set validation on Laravel. Laravel provides a unique validation for validating the unique value. many times we need to create a unique validation on many fields like SKU, slug etc…

So let’s see how to create a unique validation on Laravel.

public $rules = array(
    ‘name’ => ‘required|unique:product,slug|max:255,

I set unique validation on slug filed of product module. Now Laravel not allow to duplication value for a slug. So now assume I add a status field for products. When a status is 1 means the product is active and when status = 0 means the product is deactivated or deleted. Now I create a product with ‘simple-product’ slug after creating the product I delete that product now I never create a product with ‘simple-product’ slug every time I get a ‘Duplicate Record Found.’ validation so let’s create unique validation rules with status is the active condition.

public $rules = array(
    ‘name’ => ‘required|unique:product,slug,0,status’,

Now the unique validation fired when the record found with the active status = 1. the query fire like below.

select * from product where slug = ‘simple-product’ and status <>0;

Now unique validation search with active records only.

Now let’s see how to prevent unique validation on Edit method.change your validation rules on edit method like below.


$id passed the edited product id.

Now the unique validation query fire like below.

select * from product where slug = ‘simple-product’ and id <> $id and status =1;

Now the unique validation checks the unique condition with the active product and not with the current product. so it’s too easy to create unique validation on Laravel.

If you face any issue after using this code please write a comment.