One products has one subcategory. In my products table I have subcategory_id field. I have also set-up a belongsTo relationship between Product and Subcategory models. So I have a method which returns all products with a certain tag id. Here is my code:
public function getProductsByTag($tag_id)
{
$tag = Tag::find($tag_id);
$products = $tag->products; //belongsTo relationship
return json_encode(['products' => $products]);
}
Then on success in my ajax request I need to access the subcategory of the product like I accessed the products of the tag $tag->products
. So in Laravel it would be:
$subcategory = $product->subcategory;
I thought that product.subcategory
would do the trick but I get undefined. Here is my ajax success function:
success: function (data) {
$.each(data.products, function (i, product) {
console.log(product.subcategory);
});
},
I get undefined in my console. How can I access relationships in ajax response data?
$products = $tag->products()->with('subcategory')->get(); //belongsTo relationship
– zorx$.each(data, function (i, product) { console.log(product.subcategory); });
– Marko Milivojevic