0
0
Laravelframework~5 mins

Conditional validation in Laravel

Choose your learning style9 modes available
Introduction

Conditional validation helps check form data only when certain conditions are true. It avoids unnecessary errors and makes forms smarter.

When a field is required only if another field has a specific value.
When you want to validate a field only if the user checked a checkbox.
When you need to apply different rules based on user input choices.
When some fields depend on others and should be validated accordingly.
Syntax
Laravel
Validator::make($data, [
    'field1' => 'required',
    'field2' => 'required_if:field1,value',
]);

required_if: Makes a field required only if another field has a specific value.

You can use other conditional rules like required_unless, required_with, and required_without.

Examples
The phone field is required only if the user chooses 'phone' as their contact method.
Laravel
$request->validate([
    'email' => 'required|email',
    'phone' => 'required_if:contact_method,phone',
]);
The password confirmation is required only if the password field is present, and it must match the password.
Laravel
$request->validate([
    'password' => 'required',
    'password_confirmation' => 'required_with:password|same:password',
]);
The discount amount is required only if the discount code equals 'DISCOUNT2024'.
Laravel
$request->validate([
    'discount_code' => 'nullable|string',
    'discount_amount' => 'required_if:discount_code,DISCOUNT2024',
]);
Sample Program

This controller method validates an order form. It requires a payment method. If the method is 'card', the card number must be provided and be 16 digits. If the method is 'paypal', the PayPal email must be provided and be a valid email.

Laravel
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class OrderController extends Controller
{
    public function store(Request $request)
    {
        $validated = $request->validate([
            'payment_method' => 'required|string',
            'card_number' => 'required_if:payment_method,card|digits:16',
            'paypal_email' => 'required_if:payment_method,paypal|email',
        ]);

        return response()->json(['message' => 'Order validated successfully', 'data' => $validated]);
    }
}
OutputSuccess
Important Notes

Use conditional validation to keep forms user-friendly and avoid forcing users to fill irrelevant fields.

Laravel offers many conditional rules like required_if, required_unless, required_with, and required_without to cover different cases.

Always test your validation rules with different inputs to ensure they behave as expected.

Summary

Conditional validation checks fields only when needed.

Use Laravel's built-in conditional rules to simplify your form logic.

This makes forms easier and less frustrating for users.