Complex unique validation rule in Laravel

Author: zemna
Date: April 17, 2021
Share this:

Laravel provides unique validation rule for check unique value on a given database table.

Ref : https://laravel.com/docs/5.1/validation#rule-unique

Syntax

unique:table,column,except,idColumn,whereColumn1,whereValue1,whereColumn2,whereValue2,...

Ex1. Validate unique value in given database table

'username' => 'unique:users,username'

Ex2. Validate unique value except given ID

In mostly used when update existing record.

'username' => 'unique:users,username,'.$user->id

Ex3. Gives id column name if primary key of table isn't 'id'.

'username' => 'unique:users,username,'.$user->id.',user_id'

Ex4. Adding additional where clauses for more complex condition

If company has tag list and want to check unique value,

'name' => 'unique:tags,name,NULL,id,company_id,'.$company_id

If company has hierarchical folder list and want to check unique value per each node,

'name' => 'unique:folders,name,NULL,id,company_id,'.$company_id.',parent_id,'.$parent_id
Share this:

Leave a Reply

Your email address will not be published. Required fields are marked *

Let's connect and create
something awesome together!
2023 - Copyright, All Rights Reserved, Made by ZEMNA.NET with ❤️
crossmenu linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram