How to Use Unique Rule in Laravel Validation
In Laravel, use the
unique validation rule to ensure a field value is unique in a database table. You specify the table name and column like unique:table,column. For example, 'email' => 'unique:users,email' checks that the email is not already in the users table.Syntax
The unique rule syntax is unique:table,column,except,idColumn.
- table: The database table to check.
- column: The column to check for uniqueness (defaults to the field name if omitted).
- except: An optional ID to ignore (useful when updating records).
- idColumn: The name of the ID column (defaults to
id).
php
'field_name' => 'unique:table,column,except,idColumn'
Example
This example validates that the email field is unique in the users table. When updating a user, it ignores the current user's ID to allow keeping the same email.
php
<?php
$request->validate([
'email' => 'required|email|unique:users,email,' . $user->id,
]);Output
If the email exists in users table except for the current user ID, validation fails with an error.
Common Pitfalls
Common mistakes include:
- Not specifying the
exceptID when updating, causing false validation errors. - Omitting the column name when it differs from the field name.
- Using the wrong table name or column name.
Always double-check table and column names and use the except parameter when updating records.
php
<?php // Wrong: No except ID on update $request->validate([ 'email' => 'required|email|unique:users,email', ]); // Right: Ignore current user ID $request->validate([ 'email' => 'required|email|unique:users,email,' . $user->id, ]);
Quick Reference
| Parameter | Description |
|---|---|
| table | Database table to check for uniqueness |
| column | Column name to check (optional, defaults to field name) |
| except | ID to ignore (useful for updates) |
| idColumn | Name of the ID column (defaults to 'id') |
Key Takeaways
Use the unique rule as 'unique:table,column' to check database uniqueness.
Include the except ID when updating to avoid false validation errors.
Specify the correct table and column names to ensure proper validation.
The unique rule helps prevent duplicate entries in your database.
Laravel validation automatically returns errors if uniqueness fails.