user3653474
user3653474

Reputation: 3854

Loop through Categories and its Products in PHP Laravel

I have to create an array with the categories array and its related products i'm fetching category with all related products using this query

  $categoryData= Category::with('product')->get();

Data is beign fetched properly, using this loop to get data in the format given below:

 foreach($categoryData as $row){
            $categoriesData[] = [
                'id' => $row->id,
                'title' =>  $row->title,
            ];
          foreach($row->product as $rowproduct){
            $categoriesData['product_details'][] = [
             'product_name' => $rowproduct->name,
             'product_price' => $rowproduct->price
      ];
}
}

Format (It should be something like this) :

{
    "categoriesData": {
        "0": {
            "id": 1,
            "category_name" : "Name 1",
        "product_details": [
            {
                "id": 1,
                "product_name": Product Name,
            },
        ],
        "1": {
            "id": 2,
            ""category_name" ": "Name 2",
            "product_details": [
            {
                "id": 1,
                "product_name": product name,
            },
        },
      
   

but through present loop all product is getting saved in one array. It is not saving inside category.

Any help is highly appreciated

Upvotes: 0

Views: 1031

Answers (2)

lagbox
lagbox

Reputation: 50481

You can do this with Collection methods if you wanted to, basically just map:

$array = $categoryData->map(function ($category) {
    return [
        'id' => $category->id,
        'title' => $category->title,
        'product_details' => $category->products->map(function ($product) {
            return [
                'product_name' => $product->name,
                'product_price' => $product->price,
            ];
        }),
    ];
})->all();

Though this is going in the direction of using a transformer or API resource to format this data.

Upvotes: 1

Shaolin
Shaolin

Reputation: 434

Hi I think this is what you're looking for :

foreach ($categoryData as $key => $row) {
    $categoriesData[$key] = [
        'id' => $row->id,
        'title' => $row->title,
    ];
    foreach ($row->product as $rowproduct) {
        $categoriesData[$key]['product_details'][] = [
            'product_name' => $rowproduct->name,
            'product_price' => $rowproduct->price
        ];
    }
}

Upvotes: 0

Related Questions