3
votes

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?

2
in your controller method try this one $products = $tag->products()->with('subcategory')->get(); //belongsTo relationshipzorx
Try this $.each(data, function (i, product) { console.log(product.subcategory); });Marko Milivojevic
@zorx This works. However I have a product which has a subcategory which has a category. Now how can I access the category? Post your comment as question so I can approve it.Codearts

2 Answers

3
votes

As I said in my comment, laravel doesn't load automatically all the relations so you have to do that.

if you would like to load every time subcategories into your products so you have to update you model and add a with attribute like so :

//Product model
protected $with = ['subcategory'];

Or if you just want to do this just once, so you have to do something like :

$products = $tag->products()->with('subcategory')->get();
2
votes

I found a solution by providing a variable that holds the relationship inside the model I need. I add one variable for subcategory in my Product model and one variable for category in my Subcategory model. Here is what it looks like: In my Product model:

protected $with = array('subcategory');

In my Subcategory model:

protected $with = array('category');

Now I can access them easily from my ajax success response data.