3

In my products table, each Product has a column called retailer. In my view, I am trying to fetch and display all unique values for that retailer column from the table. Note that I only need distinct values for ONE single column, i.e. retailer. Here's my attempt:

@foreach(\App\Product::select('retailer')->groupBy('retailer')->get() as $retailer)
    {{$retailer->retailer}}
@endforeach

Here I've read that groupBy('retailers) would get the unique values. That indeed worked, but since I am passing an array $products to the view, which contains all products, I thought looping through $products would be more efficient:

 @foreach($products->select('retailer')->unique() as $retailer)
     {{$retailer}}
 @endforeach

but that didn't work.

Q: What am I doing wrong here? Is there a more efficient way to go about this? Is it better to resort to Query Builder (rather than Eloquent) in this case?

Thank you!

Community
  • 1
  • 1
Alex
  • 3,719
  • 7
  • 35
  • 57

1 Answers1

1

Try

@foreach(App\Product::distinct()->get(['retailer']) as $product)
    {{$product->retailer}}
@endforeach

EDIT

Of course you can. In your controller

$products = App\Product::distinct()->get(['retailer']);
foreach($products as $product) {
    // do your magic
}
huuuk
  • 4,597
  • 2
  • 20
  • 27
  • Is there any way that I could loop through the `$products` array instead that I pass with the view? – Alex Aug 08 '16 at 13:07