Mike Thrussell
Mike Thrussell

Reputation: 4515

how to iterate through data in Blade views (Laravel 5.2)

Within Blade, {{ dd(get_defined_vars()['__data']) }} gives me this output:

array:6 [▼
  "__env" => Factory {#152 ▶}
  "app" => Application {#2 ▶}
  "errors" => ViewErrorBag {#145 ▶}
  0 => array:1 [▼
    "question" => "question 3"
  ]
  1 => array:1 [▼
    "question" => "question 2"
  ]
  2 => array:1 [▼
    "question" => "question 1"
  ]
]

My controller builds this data like so:

foreach ($questions as $question) {
        $answer = [
            'question' => $question->question,
        ];
        $answers[] = $answer;
    }
    return view('results')->with($answers);

How do I iterate over this in Blade to display the 3 questions?

Upvotes: 0

Views: 2703

Answers (1)

devnull
devnull

Reputation: 1928

This should do the job

From laravel documentation

When passing information in this manner, $data should be an array with key/value pairs

In Controller

return view('results')->with('answers', $answers);

In blade

 @foreach($answers as $answer)
         {{ $answer['question'] }}
 @endforeach

Have a look at

https://laravel.com/docs/5.2/views#passing-data-to-views

Upvotes: 3

Related Questions