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);