Laravel unique column validation on add and update with where condition

Here we will discuss laravel all types of unique column validation rules. laravel unique field validation rule on data update. laravel unique validation with where condition. Unique validation rules in laravel 8, laravel 9.


Laravel unique column validation rules

  1. Unique column validation by table name
  2. Unique validation check by model
  3. Check unique column with id when update data
  4. Laravel unique column validation with where condition

Unique column validation by table name

When you want to validate a column same value is not available in a table then laravel provides a unique validation rule specify the table column name with table. email_address is the database table column name.

Validator::make($data, [
  'email' => 'required|unique:users,email_address' //email_address => db column name
]);

Unique validation check by model

When you want to check the unique column rule by model instead of table specify the column name with eloquent model instead of the table see below example.

Validator::make($data, [
  'email' => 'required|unique:App\Models\User,email_address'
]);

Check unique column with id when update data

When you want to check unique column validation during updating the data, We pass an ID to ignore that particular row of the table. For example, if you update user profile data and here email field is unique then you pass that user ID for ignoring this row it checks unique email in all table rows instead of that ID data.

You can pass ID by two types with Rule and without Rule see below example

//without Rule
Validator::make($data, [
  'email' => 'required|unique:users,email_address,'.$user_id,
]);
// with Rule
Validator::make($data, [
  'email' => [
	  'required',
	  Rule::unique('users', 'email_address')->ignore($user_id),
	],
]);

Laravel unique column validation with where condition

You may also use a where condition when defining validation for the unique column. In laravel you can also define unique column with other column. For example users table 'email_address' column is unique by the user_type column like, we only check the unique email address of users whose user_type is equal to 1.

Validator::make($data, [
  'email' => Rule::unique('users')->where(fn ($query) => $query->where('user_type', 1))
]);
php laravel developer anmol sharma

Anmol Sharma

I am a software engineer and have experience in web development technologies like php, Laravel, Codeigniter, javascript, jquery, bootstrap and I like to share my deep knowledge by these blogs.

Random tutorial links