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.
If you haven't already, create a new Laravel 10 project using Composer:
composer create-project laravel/laravel conditional-validation
cd conditional-validation
In this step, we'll create a route and controller for handling the validation.
php artisan make:controller ValidationController
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.
}
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),
]);
The field under validation must be present and not empty if the anotherfield field is equal to yes
, on
, 1
, "1"
, true
, or "true"
.
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');
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>
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
With everything set up, run your Laravel 10 application:
php artisan serve
You might also like: