about uscontact

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.

ZEMNA.NET

Professional software development agency estalished in Indonesia. We offers website setup, web application development, fulfillment service, and etc.
Follow us
Follow us to get latest news and tutorials.
2022 - Copyright, All Rights Reserved, Made by ZEMNA.NET with ❤️
magnifiercrossmenu