Use of Laravel validation sometimes with request class
Today we are going to understand Laravel validation Sometimes rule with request class.
Few days back I was required to use required_if rule while using a laravel validations but required_if not work like that how I want it to be.
Why do we need Laravel validation sometimes?
Here is my scenario,
I had a select box field as service type with options free and paid. So, if I select the free option then I will not need a price input field otherwise price should be required.
For this case I tried to use the required_if laravel validation rule. But I also need that price to be numeric only if it is required. That means I need to use multiple validation rules depending on the required_if rule.
One more thing, I was using a validation request class that time.
Example of Laravel validation sometimes
So, after some research I found that I can use the Laravel validation Sometimes rule by extending a method in my validation request class as given below.
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class ServiceRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'name' => 'required|max:191', 'service_type' => 'required' ]; } protected function getValidatorInstance(){ $validator = parent::getValidatorInstance(); $validator->sometimes('price', 'required|numeric', function($input) { return $input->service_type === ‘paid’; }); return $validator; } }
Here we can see that we get the parent validator instance and then apply our rule on it. Now if I select the service type paid only then price will be required and must be numeric.
That’s it, Laravel validation Sometimes rule with request class is simple and easy to use.
Hope you find this article useful.