Laravel throwing error on foreach() loop on POST

744 views Asked by At

I have a survey application built with Laravel. When users are creating answers for their questions, they enter them in to their corresponding textboxes (added dynamically with some jQuery). I have my create.blade.php code in a partial as follows:

{!! Form::open(['url' => 'surveys']) !!}
    @foreach( $questions as $question )

        <h2>{{$question->text}}</h2>
        <div id="input_fields_wrap_{{ $question->id }}">
            <div class="form-group">
                {{--{!! Form::label('answer', 'Answers:') !!}--}}
                <div class="input-group">
                    {!! Form::text('answers[]', null, ['class' => 'form-control']) !!}
                    <span class="input-group-btn"><button class="btn btn-default btn-danger remove_field" type="button">Remove</button></span>
                </div>
            </div>
        </div>
        <div id="{{ $question->id }}" class="add_answer_button btn btn-primary" style="margin-bottom:15px" type="text">Add another Answer</div>

    @endforeach

    <div class="form-group">
        {!! Form::submit('Finish Survey', ['class' => 'btn btn-primary form-control']) !!}
    </div>
{!! Form::close() !!}

Answer form submit

However when I submit the forms by clicking on the 'Finish Survey' submit button, laravel is throwing me this error:

Invalid argument supplied for foreach() (View: /home/kevin/PHSA-dev/my-follow-up/resources/views/questions/create.blade.php)

2

There are 2 answers

0
Kevbot On

My mistake was redirecting to a page that did not exist in my QuestionController. 'url' => 'questions' fixed it.

0
James Taylor On

You can avoid this fatal error by casting the variable as an array. Example:

@foreach( (array)$questions as $question )

This way if the view is rendered without $questions being an array it will appear blank rather than erring out.