Laravel Validation Check if value is not equal to a another field
Laravel

Laravel Validation Check if value is not equal to a another field

To check if a value is not equal to another field in Laravel validation, you can use a different rule. Here's an example of how to use it:

use Illuminate\Support\Facades\Validator;

$data = [
    'field1' => 'value1',
    'field2' => 'value2',
];

$validator = Validator::make($data, [
    'field1' => 'required',
    'field2' => 'required|different:field1',
]);

if ($validator->fails()) {
    // Handle validation errors
}

In this example, we have two fields field1 and field2. We are checking if field2 is not equal to field1. The different rule takes a parameter of the field name to compare against.

 

If field2 is equal to field1, the validation will fail and you can handle the error appropriately.

 

You can also use a different rule with multiple fields. For example:

$validator = Validator::make($data, [
    'field1' => 'required',
    'field2' => 'required|different:field1,field3',
    'field3' => 'required',
]);

 

In this example, we are checking if field2 is not equal to both field1 and field3.

Thank you for your time.

Get The latest Coding solutions.

Subscribe to the Email Newsletter