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

Avatar
C

Callum Davies

Senior Backend Engineer••
7954Views
5mRead
0Reactions

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.

Connect with KoderSolution 🚀

Master modern software engineering, scalable architectures, and advanced backend systems.

What's your setup?How does your production stack handle background jobs? Are you using Redis with Horizon, or cloud queues like AWS SQS?
Callum Davies
C
Written by•Senior Backend Engineer

Callum Davies

PHP & Laravel practitioner since v5.4. Big believer in thin controllers, explicit return types, and boring modular architecture that doesn't page you on weekends.

React to this article

Recommended Articles

View all articles