Tag

Unique

Browsing

Laravel is the fastest growing PHP Framework and Object-oriented framework and provides a rich library. Laravel provides a best validation library using that we can easily validate the incoming request. Today, We are going to learn about the unique validation of Laravel. Laravel unique validation is preventing from the duplicate value on the database. You can easily check the record is exists on the database or not? Using Laravel unique validation. Many times we need set the unique validation for Email, Phone, Slug, SKU etc…

Laravel unique validation

So let’s see how we can use Laravel unique validation. I want to set the unique validation on the slug field then let’s follow the validation rule.

We set the unique validation on slug field. Slug field is very useful when we are working with Blog, Product etc… module. Now, Laravel check for the slug on the database that the slug exists or not? If the slug exists then Laravel fire validation like”The slug has already existed”. So, it’s too easy to set unique validation on Laravel.

Now, Let’s write the unique validation for edit record. We need to change the validation value when we are working on edit functionality. We need to pass the current active record ID as a parameter on validation. Now, Let’s change the unique validation during edit functionality like.

Now, Let’s assume I want to edit the 7 number product then Laravel fire unique validation query like below.

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

Now, Check the unique validation working perfectly with edit record functionality.

If you face any issue on Laravel unique validation please write the comment below.