How to Validate Input Based on Condition in Laravel 10?

Nov 28, 2023 . Admin

Hi dev,

As a developer working with Laravel, I've often faced situations where input validation isn't a one-size-fits-all solution. There are instances when validation rules need to be applied based on specific conditions or criteria, introducing an additional layer of complexity to the validation logic.

In this comprehensive guide, I'll walk you through the process of validating input based on conditions in Laravel 10, a powerful and flexible PHP framework. Let's start by creating a new Laravel 10 project and configuring a form for users to input data that requires validation.

Step 1: Set Up a New Laravel 10 Project

If you haven't done so already, initiate a new Laravel 10 project using Composer:

composer create-project laravel/laravel conditional-validation
cd conditional-validation	
Step 2: Create a Route and Controller

Now, let's establish a route and controller to manage the validation process.

php artisan make:controller ValidationController	

In the generated ValidationController, craft a method for handling form submissions:

public function validateInput(Request $request)
{
    $request->validate([
        'input1' => 'required',
        'input2' => $request->input('input1') == 'specific_value' ? 'required' : 'nullable',
    ]);

    // If the validation passes, proceed with the data.
}	
1. Using required_if

Ensure the field is present and not empty if another field meets a specific condition.

use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

Validator::make($request->all(), [
    'role_id' => Rule::requiredIf($request->user()->is_admin),
]);	

Or, use a closure for more complex conditions:

Validator::make($request->all(), [
    'role_id' => Rule::requiredIf(fn () => $request->user()->is_admin),
]);	
2. Using required_if_accepted

Require the field if another field is set to 'yes,' 'on,' 1, "1," true, or "true."

3. Using required_with

Mandate the presence of the field only if specific other fields are present and not empty.

Define a route for this method in routes/web.php:
use Illuminate\Support\Facades\Route;

Route::post('/validate-input', 'ValidationController@validateInput');	
Step 3: Create a Form View

Craft a form view (in resources/views/validation-form.blade.php) where users can input data for validation:

<h2>Laravel Conditional Validation Based on Other Fields</h2>
<form method="POST" action="/validate-input">
    @csrf

    <label for="input1">Input 1</label>
    <input type="text" name="input1" id="input1">
    
    <label for="input2">Input 2</label>
    <input type="text" name="input2" id="input2">
    
    <button type="submit">Submit</button>
</form>	
Step 4: Display Validation Errors

If validation fails, Laravel will automatically redirect back to the form view and display errors. Include the following code in your form view:

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif	
Step 5: Run the Application

With everything set up, run your Laravel 10 application:

php artisan serve	
#Laravel 10