Svetoslav Dimitrov Svetoslav Dimitrov - 2 months ago 20
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', 'products.id', '=', 'shopping_list_items.product_id' )
->join('shop_lists', 'shop_lists.id', '=', 'shopping_list_items.shopping_list_id')
->select('products.product_name', 'products.id')
->where('shop_lists.id', $this->id);
}


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

{{$shoppinglists->getProduct()->first()->product_name}}


But I can't loop through it like this:

@foreach($shoppinglists->getProduct() as $sh)
{{$sh->product_name}}<br>
@endforeach


Though it doesn't show any error.

Answer

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)
    {{$sh->product_name}}<br>
@endforeach
Comments