Laravel Unique Validation with Condition Example

By Hardik Savani November 5, 2023 Category : Laravel

Greetings,

In this article, we will discuss the topic of Laravel unique validation with conditions. The purpose of this article is to provide you with a straightforward example of how to implement Laravel's unique validation for multiple columns. We will guide you through each step while explaining the process of using Laravel unique validation with a where condition. The explanation will be simple and easy to understand, allowing you to add unique validation in Laravel with conditions effortlessly. Simply follow the steps outlined below for implementing Laravel unique validation with conditions.

To implement unique validation with condition using Laravel's Rule class, you can follow these steps:

1. Import the Rule class at the top of your PHP file:

use Illuminate\Validation\Rule;

2. Define your validation rule with the Rule class, including the condition:

$request->validate([

'field_name' => [

'required',

Rule::unique('table_name')->where(function ($query) use ($condition) {

$query->where('column_name', $condition);

}),

],

]);

Replace 'field_name' with the name of the field you want to validate, 'table_name' with the name of your database table, 'column_name' with the name of the column you want to apply the condition on, and $condition with the value you want to check against.

Example Code:

Here is an example with customer validation rules in controller file:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Illuminate\Validation\Rule;

class CustomerController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index()

{

return view('customers.index');

}

/**

* Write code on Method

*

* @return response()

*/

public function store(Request $request)

{

$request->validate([

'email' => [

'required',

'email',

Rule::unique('customers')->where(function ($query) use ($condition) {

$query->where('status', 1)

->where('is_active', 1);

}),

],

]);

dd("Do Tasks");

}

}

In this example, the email field will be required and must be unique in the customers table, but only where the status column is equal to the provided condition value.

Note that you need to replace 'customers' with the actual name of your customers table.

This approach allows you to provide dynamic conditions for your unique validation rules in Laravel.

I hope it can help you...

Tags :
Shares