Posted: 24-07-2020

Unique validation in Laravel

Unique validation in Laravel

Laravel provides a rich set of validation helpers.

The unique method validate if a given column not exist within the given database table.

unique:table,column,except,idColumn 

for example if you need to validate if a given product_code not exists in products table.

'product' => 'unique:products,product_code'

How to force validator to ignore a given id

Sometimes, you may wish to ignore a given ID during the unique check, for example, when you update the product record.
In this situation you can add the except value to your rule.

'product' => 'unique:products,product_code,$product->id'

or to instruct the validator to ignore the product's ID, we'll use the Rule class to fluently define the rule.

Rule::unique('products')->ignore($product)

Hereafter the query that Laravel perform to check if unique value already exists.

SELECT Count(*) AS aggregate 
FROM   `products` 
WHERE  `code` = 5 
       AND `id` <> 10 

How to validate two columns unique constraint

In some situation you need to validate unique constraint on two fields

$table->unique(['user_id', 'research_id']);

Using the Rule class you can fluently define your rule:

Rule::unique('research_users','research_id')
->where('user_id',$research_user->user_id)
->ignore($research_user->id))

Looking inside the Illuminate\Validation\Rules\Unique you can see the validation invoke the following pattern unique:% s,% s,% s,% s,% s 

/**
 * Convert the rule to a validation string.
 *
 * @return string
 */
public function __toString()
{
    return rtrim(sprintf('unique:%s,%s,%s,%s,%s',
        $this->table,
        $this->column,
        $this->ignore ?: 'NULL',
        $this->idColumn,
        $this->formatWheres()
    ), ',');
}

This produce a validation string like this:

 You can find more about unique rule at Laravel official documentation.