如何在Blade视图中迭代数据(Laravel 5.2)

时间:2016-03-07 14:56:13

标签: loops laravel laravel-5 blade laravel-blade

在Blade中,{{ dd(get_defined_vars()['__data']) }}为我提供了这个输出:

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"
  ]
]

我的控制器像这样构建这些数据:

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

如何在Blade中迭代显示3个问题?

1 个答案:

答案 0 :(得分:2)

这应该做的工作

来自laravel文档

  

以这种方式传递信息时,$ data应该是一个数组   键/值对

在控制器中

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

在刀片中

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

看看

  

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