经过数小时的试用和失败后,我卡在我的刀片模板中的foreach循环中我需要一些帮助。
我的控制器
public function menue() {
$restaurants = User::with('articles')->get();;
return view('pages.menues')->withRestaurants($restaurants);
}
我的foreach
@foreach($restaurants as $restaurant)
<div class="panel panel-default">
<div class="panel-heading">
@foreach($restaurant->articles as $article)
{{$article->title}}
<span class="float-right">{{$article->published_at}}</span>
@endforeach
</div>
<div class="panel-body">
@foreach($restaurant->articles as $article)
{{$article->body}}
@endforeach
{{$restaurant->name}}
</div>
</div>
@endforeach
这就是我试图循环的原因:
{
"id":1,
"name":"Sam",
"email":"sam@me.com",
"created_at":"2016-07-26 15:03:51",
"updated_at":"2016-07-27 15:39:55",
"articles":[
{
"id":1,
"user_id":1,
"title":"Monday Afternoon",
"body":"got it",
"created_at":"2016-07-27 15:31:05",
"published_at":"2016-07-27 15:30:00",
"excerpt":null,
"updated_at":"2016-07-27 15:31:05"
},
{
"id":3,
"user_id":1,
"title":"Good Morning Wednesday",
"body":"lorem ipsum",
"created_at":"2016-07-27 11:38:37",
"published_at":"2016-07-27 11:38:00",
"excerpt":null,
"updated_at":"2016-07-27 11:38:37"
},
{
"id":4,
"user_id":1,
"title":"Good Morning Thursday",
"body":"lorem ipsum ",
"created_at":"2016-07-27 11:39:14",
"published_at":"2016-07-28 14:38:00",
"excerpt":null,
"updated_at":"2016-07-27 11:39:14"
},
{
"id":5,
"user_id":1,
"title":"Wednesday Afternoon",
"body":"Hallo Welt",
"created_at":"2016-07-27 14:55:00",
"published_at":"2016-07-27 14:54:00",
"excerpt":null,
"updated_at":"2016-07-27 14:55:00"
}
]
}
结果是我只获得了2个帖子而不是4个帖子。他们每个都包含其他帖子。如何在我的视图中单独显示所有4个帖子?
答案 0 :(得分:1)
试试这个
@foreach($restaurants as $restaurant)
@foreach($restaurant->articles as $article)
<div class="panel panel-default">
<div class="panel-heading">
{{$article->title}}
<span class="float-right">{{$article->published_at}}</span>
</div>
<div class="panel-body">{{$article->body}}</div>
</div>
@endforeach
@endforeach