2016-07-27 66 views
0

我嘗試在我的視圖中對某些數據進行dsiplay處理,但不知道如何循環處理多維數組。Laravel從關係表中提取的雄辯數據

我的控制器是:

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":"[email protected]", 
    "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" 
     } 
    ] 
} 

我的問題是如何能我訪問/顯示我的$餐廳變量內的「articles」數組?

回答

0

您可以創建一個:

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

我訪問$餐廳 - >名稱,也是文章陣列 –

+0

裏面的屬性如果在你的foreach仔細觀察你正在訪問{{$餐廳 - > body}}這是一個子數組,你的foreach只循環一次。身體是一個關鍵,這是我在你的輸出中看到的3倍。當foreach只循環一次時,{{$ restaurant-> body}}不知道從3中獲取哪個主體。這就是爲什麼你需要另一個foreach循環,正如我上面提到的。 –