I have three tables:
productstable (id,name)ingredientstable (id,ingredient_name)products_ingredientstable (product_id,ingredient_id)
I have a relation defined in Product
public function ingredients(){
return $this->hasMany('App\ProductIngredient','product_id','id');
}
When I am listing products using
$products = Product::where('category_id',$cat->id)->with('ingredients')->get();
I am getting this output
"products": [{
"id": 1,
"name": "Hesp",
"category_id": 1,
"ingredients": [{
"id": 41,
"product_id": 1,
"ingredient_id": 4,
},
{
"id": 42,
"product_id": 1,
"ingredient_id": 5,
}]
}]
Which is right.
What I want is to add the ingredient name in ingredients list like this
"products": [{
"id": 1,
"name": "Hesp",
"category_id": 1,
"ingredients": [{
"id": 41,
"product_id": 1,
"ingredient_id": 4,
"ingredient_name": "some name" // I want to add this field
},
{
"id": 42,
"product_id": 1,
"ingredient_id": 5,
"ingredient_name": "some name" // I want to add this field
}]
}]
I want to return this as JSON to use in API not in blade where I can call other relations.
How can I achieve this?