3
votes

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?

1
Both relations have a belongTo, that's not right. Product should probably be hasMany. - Andrei
@Scarwolf it seems like, in your view, you are getting an array instead of a collection. Could you please check using $product['image']['thumbnail'] - jaysingkar
Andrew: Ooh, you're right. Changed it to hasOne, still the same, though. (1 image row for each product). @jaysingkar That's working. Why do laravel returns an array though? How can I change that back to a collection...? - xTheWolf
sorry @Scarwolf I'm not sure about that. However,you can try passing $categories directly without adding it to $data array. - jaysingkar
Using with may be overriding your relationships. If you have relationships all the way down, try using just Categories::all(), then access everything through the relationships. - aynber

1 Answers

0
votes

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. :)