4
//CartController
$itens = CartItem::where('id_cart', $cart->id)->with('product')->get();
return response()->json($itens);

This code returns a JSON with the data of the cart item and the relative product. But I also want to return the images of the product, which is in the ProductImages table.

In my model CartItem.php I have

 public function product(){
    return $this->belongsTo('App\Product', 'id_product');
}

In my model Product.php I have

  public function images(){
    return $this->hasMany('App\ProductImages', 'id_product');
}

But, if I do

 $itens = CartItem::where('id_cart', $carrinho->id)->with('product')->with('image')->get();

I get the error

Call to undefined relationship [images] on model [App\CartItem]

4 Answers 4

6

You can try it as:

CartItem::where('id_cart', $carrinho->id)->with('product.images')->get();

To eager load nested relationships, you may use "dot" syntax.

Docs

Sign up to request clarification or add additional context in comments.

Comments

2

You should load two tables by using with():

CartItem::where('id_cart', $cart->id)
        ->with('product', 'product.images')
        ->get();

You can read an explanation here (see Nested Eager Loading section).

Comments

2

you should make use of the nested eager load function:

$books = App\Book::with('author.contacts')->get();

https://laravel.com/docs/5.3/eloquent-relationships#eager-loading

Comments

0

Just use like this

$itens = CartItem::where('id_cart', $carrinho->id)->with('product','images')->get();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.