Svetoslav Dimitrov Svetoslav Dimitrov - 1 month ago 11x
PHP Question

Laravel 5. How to iterate through Eloquent properties

I have the following function in Controller:

public function getProduct()
return Product::join('shopping_list_items', '', '=', 'shopping_list_items.product_id' )
->join('shop_lists', '', '=', 'shopping_list_items.shopping_list_id')
->select('products.product_name', '')
->where('', $this->id);

This code in the view works perfectly and shows product name:


But I can't loop through it like this:

@foreach($shoppinglists->getProduct() as $sh)

Though it doesn't show any error.


Your getProduct() method returns an instance of the Database Builder, not the collection, that is why you can do ->first(), which basically does a fetch limit 1 and gets you the object.

So, you need to call the ->get() or maybe paginate() to actually do a fetch of the data to the database and obtain the collection of objects.

So, bottom line, just do:

@foreach($shoppinglists->getProduct()->get() as $sh)