简体   繁体   中英

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.

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

As @Carlos explained, you need to use get() to get values from database.

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)
->get();
}

This will return you a JSON object. If you need an array output from this query, use pluck('filed name'); instead of get(); In your view, use

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM