nanadjei2's avatar

Array collective issue.

I am building an E-Commerce app where I want to loop through a results but anytime I try I get an error Property [main_image] does not exist on this collection instance..

This is my controller:

  $latestProductWithOptions = ProductProductOption::with('product')
        ->orderBy('product_id', 'desc')->take(4)->get();
    
    $productImages = [];

    foreach ($latestProductWithOptions as $product) {
        
        echo $productImages[] = $product->product->productImage;
    }
    

$productImages return;
[{"id":6,"product_id":10,"main_image":"1513179347.jpg","thumbnail":"","created_at":"2018-01-11 18:02:52","updated_at":"2018-01-11 18:02:52"}][{"id":3,"product_id":6,"main_image":"1513179348.jpg","thumbnail":"","created_at":"2018-01-11 18:02:52","updated_at":"2018-01-11 18:02:52"}][{"id":10,"product_id":5,"main_image":"1556272478.jpg","thumbnail":"","created_at":"2018-01-11 18:02:52","updated_at":"2018-01-11 18:02:52"}][{"id":10,"product_id":5,"main_image":"1556272478.jpg","thumbnail":"","created_at":"2018-01-11 18:02:52","updated_at":"2018-01-11 18:02:52"}]

 

foreach($productImages as $product) {
        echo $product->main_image;
    }

    die();

I can see main_image in the results but anytime I try to loop through and pull main_image out, i get an error "Property [main_image] does not exist on this collection instance." Kindly help me please. Thank you.

0 likes
2 replies
Snapey's avatar

You have an array not a collection.

either

foreach($productImages as $product) {
        echo $product['main_image'];
    }

or make into a collection

But why not just ask eloquent for the images as a collection in the first place?

1 like
nanadjei2's avatar

When I tried your solution I got Undefined index: main_image.

You mean I should do something like:

foreach ($latestProductWithOptions as $product) {
        $productImages[] = ProductImage::where('product_id', $product->product_id)->get();
        
    }

Please or to participate in this conversation.