My Profile Photo

David Freund

Business Analyst, amateur Developer (PHP, Ruby - in my leisure time and with mixed results)

Validate multi-entry forms with Laravel

While working on a new Laravel Application, I needed a solution for multi-entry validation: Users should be able to add one or many persons to an event and the input should still be validated.

Laravels standard validation approach is based on static rules and messages to validate forms and/or to save models ## Prerequiste – setting up the form

The dynamic validation requires that the form entries follow the pattern Input[key][field], for instance:

<input type='text' name='guest[1][firstname]'>
<input type='text' name='guest[1][lastname]'>
<!-- Second entry -->
<input type='text' name='guest[2][firstname]'>
<input type='text' name='guest[2][lastname]'></pre>

I actually used UUIDs as keys that were dynamically created via Javascript (see Stackoverflow) when a new person was added.


Before the validation is called, the rules are dynamically defined based on the data array (here using the Laravel dot-Notation):

$data = Input::all();
if ( array_key_exists ('person', $data) )
	foreach ($data['person'] as $key => $i)
		$rules['person.'.$key.'.firstname'] = 'required';
		$messages['person.'.$key.'.firstname.required'] =
		$rules['person.'.$key.'.lastname'] = 'required';
		$messages['person.'.$key.'.lastname.required'] =
$validator = Validator::make($data , $rules, $messages);