xTheWolf
xTheWolf

Reputation: 1886

Laravel Relationship working, but showing it -> Trying to get property of non object

In my Controller I have:

public function showMainPage()
{
        $categories = Category::with('subcategories.products.prices', 'subcategories.products.image')->get();

        $data = array(
          "categories" => $categories,
        );

        return view('index')->with($data);
}

When I reference this in my view like this:

@foreach($subcategory->products as $product)
    <img src="{{ $product->image->thumbnail }}" alt="">

I get a Trying to get property of non-object error.

This is my relationship:

Product.php

public function image()
    {
        return $this->belongsTo('App\ProductImage');
    }

This is my ProductImage Relationship:

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

What is wrong there?

Upvotes: 3

Views: 218

Answers (1)

Ketav
Ketav

Reputation: 770

As per your question, You joined two table with relationship. When you fetch data from categories table it will return categories and product data.

As per given link by you: http://pastebin.com/U3FAtcsK, your $data variable contain this type of hierarchy.

category 
  subcategories
    products
      prices
      image

you are trying to display data of image array.

you have to fetch image data like this.

$categories->subcategories->product->image->thumbnail

Understand your Array Hierarchy. You didn't nothing wrong. :)

Upvotes: 0

Related Questions