Alex
Alex

Reputation: 3855

How to fetch unique values for a single column in Laravel 5.2?

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!

Upvotes: 3

Views: 7674

Answers (1)

huuuk
huuuk

Reputation: 4795

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
}

Upvotes: 1

Related Questions