How to Validate Input Based on Condition in Laravel 10

As a Laravel developer, I've often encountered scenarios where input validation is not a one-size-fits-all solution. Sometimes, you need to apply validation rules based on specific conditions or criteria, which adds an extra layer of complexity to your validation logic. I

n this step-by-step guide, I'll share my insights on how to validate input based on conditions in Laravel 10, a versatile and powerful PHP framework. We'll start by creating a new Laravel 10 project and setting up a form where users can input data for validation.

So, let's see how to validate input based on condition in laravel 10, laravel validation rules, laravel conditional validation based on other fields, required_if, required_with, when validation.

Step 1: Set Up a New Laravel 10 Project

If you haven't already, create a new Laravel 10 project using Composer:

composer create-project laravel/laravel conditional-validation
cd conditional-validation

 

Step 2: Create a Route and Controller

In this step, we'll create a route and controller for handling the validation.

php artisan make:controller ValidationController

In the generated ValidationController, create a method for handling the form submission:

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

    // If the validation passes, you can proceed with the data.
}

 

1. required_if

The field under validation must be present and not empty if the anotherfield field is equal to any value.

use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
 
Validator::make($request->all(), [
    'role_id' => Rule::requiredIf($request->user()->is_admin),
]);
 
Validator::make($request->all(), [
    'role_id' => Rule::requiredIf(fn () => $request->user()->is_admin),
]);

 

2. required_if_accepted

The field under validation must be present and not empty if the anotherfield field is equal to yeson1"1"true, or "true".

 

3. required_with

The field under validation must be present and not empty only if any of the other specified 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

Create a form view where users can input data for validation. In resources/views/validation-form.blade.php, add a form with input fields:

<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 the validation fails, Laravel will automatically redirect back to the form view and display validation errors. Add the following code to your form view to display these errors:

@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

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS