jeudi 24 mars 2016

Laravel 5.2 nested foreach

I have 2 models: Categories and Items. I dont know how to make foreach loop with nested array.

Category Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{

    public static function getAll() {

        $categories= Category::orderBy('id', 'ASC')->get();

        return $categories;

    }

    public function items() {

        return $this->hasMany('App\Item', 'category_id');

    }

Item Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{

    public static function getAll() {

        $items = Item::orderBy('id', 'DESC')->get();

        return $items;

    }

    public function category() {

        return $this->belongsTo('App\Category');

    }

}

In my controller I am doing this:

foreach($categories as $category ) {

    $data['categories'][] = [
        'id' => $category ->id,
        'name' => $category ->name,
        'items_count' => ?
    ];

}

I need to get something like this.

{
  "categories": [
    {
      "id": 1,
      "name": "cat_name_1",
      "items_count": 6,
         "items": [
           {
             "id": "1",
             "name": "item_name",
             "category_id": "1",
           }
          ],
    },
    {
      "id": 2,
      "name": "cat_name_1",
      "items_count": 7,
         "items": [
           {
             "id": "2",
             "name": "item_name",
             "category_id": "2",
           }
          ],
    },
    {
      "id": 3,
      "name": "cat_name_1",
      "items_count": 4,
         "items": [
           {
             "id": "3",
             "name": "item_name",
             "category_id": "3",
           }
          ],
    },
   ]
}

Help me to improve my code.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire