subarkah's avatar

Returns all product data by category in json format

I have one product table. Each product has a category. The category names are also in the same table. How do you display product data based on each category?

I want to return a json response like this

{
  "result" : "true",
  "data" : 
    [
        {
            "category" : "drink",
            "product" : [
                    {
                        "name" : "Ice Juice",
                        "price" : "1921",
                    }, 
                    {
                        "name" : "Tea",
                        "price" : "232",
                    }
            ]  
        }, 
        {
            "category" : "food",
            "product" : [
                {
                    "name" : "fried rice",
                    "price" : "1212",
                },
                {
                    "name" : "chicken",
                    "price" : "1212",
                },
            ]
         }
    ]
}

This is my unfinished controller

$category = DB::table('product')->select('category_name', 'name', 'price')
                ->where('category_name', '!=', '')
                ->groupBy('category_name')
                ->get();
                
                if(!$category) {
                    return response()->json([
                        'result' => 'false',
                        'error' => 'Product not found'
                    ], 400);
                }
            
    
            return response()->json([
                'result' => 'true',
                'data' => $category,
            ], 200);
0 likes
4 replies
a4ashraf's avatar

@subarkah

try this


$category = DB::table('product')->select('category_name', 'name', 'price')
                ->where('category_name', '!=', '')
                ->groupBy('category_name', 'name',
    			function ($item) {
        			return 'product';
    			})
                ->get();
 

one tip for you should use API Resources for this kind of output

see the documentation

https://laravel.com/docs/8.x/eloquent-resources

s4muel's avatar
s4muel
Best Answer
Level 50

this is as far as i can get:

$products = Product::all();

$grouped = $products->mapToGroups(function ($item, $key) {
    return [$item['category_name'] => $item];
})->map(function ($item, $key) {
    $products = $item->map(function($item, $key) {
        return $item->only('name', 'price');
    });
    return ['product' => $products];
})->map(function ($item, $key) {
    return ['category' => $key, 'product' => $item['product']];
})->values();

dump($grouped);
dump($grouped->toJson(JSON_PRETTY_PRINT));

plus this

return response()->json([
                'result' => 'true',
                'data' => $grouped,
            ], 200);

here is the playground: https://laravelplayground.com/#/snippets/79375205-98e9-40b3-bf4f-9bfb455a35de

Please or to participate in this conversation.