Yousef Altaf
Yousef Altaf

Reputation: 2773

laravel : return json data from an array

I have foreach I need return each object in this array in JSON

Let me present my controller first

$childCategory = ChildCategory::whereProductCategoryId( $catId )->get();
                $data          = array();
                foreach ( $childCategory as $childCat ) {
                    $checkChildes = ChildCategoryTwo::whereChildCategoryId( $childCat->id )->count();
                    $hasChildes   = $checkChildes > 0 ? "Yes" : "No";

                    $data[] = $childCat->id;
                    $data[] = $childCat->image;
                    $data[] = $childCat->bg_color;
                    $data[] = $childCat->product_category_id;
                    $data[] = $childCat->translations[0]->name;
                    $data[] = $childCat->translations[1]->name;
                    $data[] = $hasChildes;
                }

                return response()->json( [$data] );

the output of data comes like this

    [
        1,
        "1561015312.png",
        "#a9dabf",
        1,
        "Drinks",
        "No",
        2,
        "1562500737.jpg",
        null,
        1,
        "Drinks",
        "Yes"
    ]

the output is right but the format is wrong, I need it to output something like this

[
      {
            id : 1,
            image : "1561015312.png",
            color : "#a9dabf",
            parent_cat : 1,
            name : "Drinks",
            has_child : "No",
      },
      {
            id : 2,
            image : "1562500737.jpg",
            color : null,
            parent_cat : 1,
            name : "Soda Drinks",
            has_child : "Yes"
      }
]

Upvotes: 0

Views: 81

Answers (1)

udit rawat
udit rawat

Reputation: 221

Try with this

$childCategory = ChildCategory::whereProductCategoryId( $catId )->get();
$data = array();

foreach ( $childCategory as $childCat ) {
    $checkChildes = ChildCategoryTwo::whereChildCategoryId( $childCat->id )->count();
    $hasChildes   = $checkChildes > 0 ? "Yes" : "No";

    $data[] = [
        'id' => $childCat->id,
        'image' => $childCat->image,
        'color' => $childCat->bg_color,
        'parent_cat' => $childCat->product_category_id,
        'name' => $childCat->translations[0]->name,
        'has_child' => $hasChildes
    ];
}

return response()->json( $data );

Upvotes: 2

Related Questions