来自关系表的Laravel雄辩数据

时间:2016-07-27 15:01:43

标签: php arrays laravel foreach

我尝试在我的视图中删除一些数据,但不知道如何通过多维数组进行循环。

我的控制器是:

public function menue() {
  $articles = Article::nowpublished()->get();
  //$restaurants = User::all();
  $restaurants = User::with('articles')->get();;


  return view('pages.menues')->withArticles($articles)->withRestaurants($restaurants);
}

这就是我的观点:

@foreach($restaurants as $restaurant)

          <div class="panel panel-default">
              <div class="panel-heading">
                <span>{{$restaurant}}</span>
                <span class="float-right">{{$restaurant->published_at}}</span>
              </div>

              <div class="panel-body">
                  {{$restaurant->body}}
              </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"
      }
   ]
}

我的问题是如何在$ restaurant变量中访问/显示“articles”数组?

1 个答案:

答案 0 :(得分:0)

您可以创建一个:

@foreach($restaurant->articles as $article)
    {{$article->id}}
@endforeach