Search code examples
laravel-5laravel-5.4laravel-validation

How to validate an unknown number of fields in a Laravel form


I'm using Laravel 5.4, and have a form that's populated with questions from a database, with each question requiring a 'score' using radio buttons valued 1 thru 10. I need to accommodate an unknown number of questions, and I need validation to test that all questions have a score selected. All the radio button groups are are named q_ followed by the question_id (e.g. q_1, q_2, etc). I suppose this could all be done manually, but Laravel is such a powerful framework I have to think there's a "Laravel" way of doing this. Anyone have any suggestions?


Solution

  • I suggest you avoid giving them prefixed names, and create an actual array using something like the following;

    <input type="checkbox" name="question[{{ $question->id }}]" ...>
    

    Now in your controller method you can just do;

    $questions = $request->input('questions');
    

    And your validator rules can look like the following;

    $request->validate([
        'questions.*' => ['required', 'string']
    ]);
    

    Laravel lets you validate arrays in many way, check out the documentation.