Last Updated: February 25, 2016
·
17.85K
· ash

Laravel Validator: Require fields based on other inputs

I needed a way to conditionally make fields required in the Laravel Validator. For example, 'What is your preferred PHP framework?' should only be required if 'Do you use a framework?' is set to '1'.

This is possible by extending the Validator class as I've described in this Gist (https://gist.github.com/4176954). You can then define validation rules such as the following:

$rules = array(
    'uses_framework' => 'required',
    'preferred_framework' => 'required_if_attribute:uses_framework,==,1'
);

2 Responses
Add your response

Thanks - This is very useful.
I'd like to take it a step further and make the fields "appear" within the page only when required, i.e. if "I use a framework" is set to 1, then make field "Which framework do you use" appear.

Is this something you've done, or do you know where I can find some sample laravel and/or boilerplay code?

over 1 year ago ·

you can do this in your controller:

$validator = Validator::make($data = Input::all(), Framewrok::$rules);

$validator->sometimes('preferredframework', 'required', function($input)
{
return $input->uses
framework == 1;
});

reference: http://laravel.com/docs/validation#conditionally-adding-rules

over 1 year ago ·