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.
Connect with KoderSolution 🚀
Master modern software engineering, scalable architectures, and advanced backend systems.
Read more architectural deep-dives, systems tutorials, and engineering guides on kodersolution.com.
Subscribe to @kodersolution for concise, animated system design breakdowns and technical shorts.
Follow our official page for daily development tips, architecture discussions, and community updates.
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.