Skip to content

Mastering Laravel 12 Conditional Validation

Master Laravel 12 conditional validation with practical tips, examples, and best practices to handle dynamic form rules efficiently. Perfect for developers.

Dasun Kalupahana 5 min read 887 views 0 comments

Introduction

Laravel 12’s validation system is a powerhouse for ensuring data integrity in web applications. One of its standout features is conditional validation, which allows you to apply validation rules based on the values of other fields. This makes your forms smarter, more flexible, and user-friendly by only enforcing rules when specific conditions are met. Whether you’re building a multi-step form, an API, or a dynamic user interface, mastering conditional validation is a game-changer.

In this guide, we’ll explore how to use Laravel conditional validation rules, such as required_if, required_with, and Rule::when, with practical examples. By the end, you’ll be equipped to handle complex validation scenarios with ease.

 

Why Conditional Validation Matters

Conditional validation is essential when certain fields should only be required or validated under specific circumstances. For example:

  • A field like company_name might only be required if the user indicates they are employed.
  • A credit_card_number might only be needed if the payment method is set to “credit card.”
  • Validation rules might differ based on a user’s role (e.g., admin vs. regular user).

Laravel provides built-in rules and methods to handle these scenarios elegantly, reducing the need for complex custom logic in your controllers.

 

Key Conditional Validation Rules

Laravel offers several validation rules and methods to implement conditional logic. Here are the most commonly used ones:

  1. required_if: Makes a field required if another field has a specific value.
  2. required_unless: Makes a field required unless another field has a specific value.
  3. required_with: Requires a field if another specified field is present and not empty.
  4. required_without: Requires a field if another specified field is not present or empty.
  5. sometimes: Applies validation rules only if the field is present in the input.
  6. Rule::when: Allows for custom conditional logic using a fluent interface.
  7. Closure-based Rules: Provides fine-grained control for complex validation scenarios.

Let’s dive into practical examples to see these rules in action.


Example 1: Using required_if for Employment Status

Scenario: You have a form where users indicate their employment status (is_employed). If they select “yes,” the company_name field becomes required; otherwise, it can be empty.

Code Example:

use Illuminate\Http\Request;

public function store(Request $request)
{
    $request->validate([
        'is_employed' => 'required|in:yes,no',
        'company_name' => 'required_if:is_employed,yes|nullable|string|max:255',
    ]);

    // Proceed with storing the data
    return response()->json(['message' => 'Form submitted successfully']);
}

Explanation:

  • The is_employed field must be either “yes” or “no.”
  • The company_name field is required only if is_employed is “yes.” The nullable rule allows it to be empty when not required.
  • If validation fails, Laravel automatically redirects back with error messages (or returns a JSON response for APIs).

Form View (resources/views/form.blade.php):

<form method="POST" action="/submit">
    @csrf
    <label for="is_employed">Employment Status</label>
    <select name="is_employed" id="is_employed">
        <option value="yes">Yes</option>
        <option value="no">No</option>
    </select>

    <label for="company_name">Company Name</label>
    <input type="text" name="company_name" id="company_name">

    <button type="submit">Submit</button>

    @if ($errors->any())
        <div class="alert alert-danger">
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif
</form>

Output:

  • If is_employed is “yes” and company_name is empty, validation fails with an error: “The company name field is required.”
  • If is_employed is “no,” company_name can be left blank without triggering an error.
Example 2: Using required_with for Address Fields

Scenario: In a form, the state field is required only if the country field is filled in.

Code Example:

use Illuminate\Http\Request;

public function store(Request $request)
{
    $request->validate([
        'country' => 'nullable|string|max:128',
        'state' => 'required_with:country|string|max:128',
    ]);

    // Proceed with storing the data
    return response()->json(['message' => 'Address saved successfully']);
}

Explanation:

  • The country field is optional (nullable).
  • The state field is required only if country is present and not empty.
  • Both fields are validated to be strings with a maximum length of 128 characters.

Use Case: This is ideal for forms where users might optionally provide address details, but if they start filling in the address, certain fields become mandatory.

Example 3: Using Rule::when for Role-Based Validation

Scenario: You’re building a form where validation rules differ based on the user’s role (role). For example, if the role is “teacher,” additional fields like credentials are required; if the role is “student,” a grade_level is required.

Code Example:

use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

public function store(Request $request)
{
    $request->validate([
        'role' => 'required|in:teacher,student',
        'name' => 'required|string|max:255',
        'email' => 'required|email|unique:users',
        'credentials' => Rule::when(
            $request->role === 'teacher',
            ['required', 'array'],
            ['nullable']
        ),
        'grade_level' => Rule::when(
            $request->role === 'student',
            ['required', 'integer', 'between:1,12'],
            ['nullable']
        ),
    ]);

    // Proceed with storing the data
    return response()->json(['message' => 'User registered successfully']);
}

Explanation:

  • The Rule::when method takes three arguments: a condition, rules to apply if the condition is true, and default rules if the condition is false.
  • If role is “teacher,” the credentials field must be a non-empty array.
  • If role is “student,” the grade_level field must be an integer between 1 and 12.
  • Fields not required for a given role are marked as nullable to allow empty values.

Use Case: This approach is perfect for dynamic forms where validation requirements vary based on user input, such as registration forms for different user types.

Example 4: Closure-Based Custom Validation

Scenario: You need to validate a promo_code field to ensure it’s in uppercase, but only if it’s provided.

Code Example:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

public function store(Request $request)
{
    $request->validate([
        'promo_code' => [
            'nullable',
            'string',
            function ($attribute, $value, $fail) {
                if (strtoupper($value) !== $value) {
                    $fail('The promo code must be in uppercase.');
                }
            },
        ],
    ]);

    // Proceed with storing the data
    return response()->json([
            'message' => 
            'Promo code validated successfully'
    ]);
}

Explanation:

  • The promo_code field is optional (nullable).
  • If provided, a closure-based rule checks if the value is entirely uppercase.
  • If the check fails, a custom error message is returned.

Use Case: Closure-based validation is ideal for one-off, specific validation logic that doesn’t warrant a reusable custom rule class.

 

Best Practices for Conditional Validation

  1. Use Form Requests for Reusability: Move validation logic to a dedicated FormRequest class to keep controllers clean. For example:
php artisan make:request UserStoreRequest

Then, in app/Http/Requests/UserStoreRequest.php:

use Illuminate\Validation\Rule;

class UserStoreRequest extends FormRequest
{
    public function rules(): array
    {
        return [
            'is_employed' => 
              'required|in:yes,no',
            'company_name' => 
              'required_if:is_employed,yes|nullable|string|max:255',
        ];
    }

    public function messages(): array
    {
        return [
            'company_name.required_if' => 
            'Please provide your company name if you are employed.',
        ];
    }
}

Use it in your controller:

public function store(UserStoreRequest $request)
{
    // Validated data is automatically available
    return response()->json(['message' => 'Form submitted successfully']);
}

2. Provide Clear Error Messages: Customize error messages to guide users effectively, as shown in the messages method above.

3. Test Validation Logic: Write unit tests to ensure your conditional validation behaves as expected under different scenarios.

4. Document Your Logic: Add comments or documentation to explain complex conditional rules, making it easier for other developers to understand your code.

 

Conclusion

Conditional validation in Laravel 12 empowers developers to create dynamic, user-friendly forms that adapt to user input. By leveraging rules like required_if, required_with, Rule::when, and closure-based validation, you can handle complex scenarios without cluttering your codebase. The examples provided in this guide demonstrate practical applications, from simple employment forms to role-based validation and custom rules.

Start implementing these techniques in your Laravel projects to ensure data integrity and enhance user experience. For more details, check the official Laravel 12 Validation Documentation.

Happy coding, and make your forms smarter with Laravel 12!

Free resources for this topic

Code snippets and fixes for this topic

Get one practical tip every week

New tutorials, fixes and free cheat sheets from DEV Talk, straight to your inbox. No spam, unsubscribe in one click.

Free download: Laravel interview questions (PDF)

Have a question about this post?

Ask the community: other developers and the author can answer.

Ask the community

Get notified about new articles

One click, no email needed. Turn it off anytime with the bell at the top.

Get new articles on your iPhone

Add DEV Talk to your Home Screen, open it, then tap the bell.

Rate this post
0.0
Share

Enjoying the content?

If this article helped you, you can support the author with a coffee. It keeps new posts coming.

Buy me a coffee (opens in a new tab)

Comments 0

Be kind. Comments with links are reviewed before they appear.

No comments yet

Be the first to share your thoughts.

Get new articles in your inbox

Practical tutorials and deep dives, about once a week. No spam, unsubscribe anytime.

Privacy policy

Add DEV Talk to your Home Screen

  1. 1 Tap the Share button in Safari's toolbar.
  2. 2 Scroll down and tap Add to Home Screen.
  3. 3 Tap Add. Open it from the Home Screen to read like an app and to turn on notifications with the bell.

We use cookies to improve your experience and analyze traffic. By continuing, you agree to our Privacy Policy.