Home > Software engineering >  Laravel 9 - Eloquent group results of query
Laravel 9 - Eloquent group results of query

Time:10-10

I am looking for a way to take one query in Eloquent to get all search results, and then take those results, group them by type, and output the different types.

I currently have this setup to get all my search results:

$listings = Listing::where('listings.expiration_date', $date_operator, date('Y-m-d H:i:s'));

$listing->where(function($query) use ($keyword) {
                         $query->where('listings.lot_number', 'LIKE', '%'.$keyword.'%')
                                    ->orWhere('listings.title', 'LIKE', '%'.$keyword.'%')
                                    ->orWhere('listings.brand', 'LIKE', '%'.$keyword.'%')
                                    ->orWhere('listings.grade', 'LIKE', '%'.$keyword.'%')
                                    ->orWhere('listings.tags', 'LIKE', '%'.$keyword.'%')
                                    ->orWhere('listings.player', 'LIKE', '%'.$keyword.'%');
                         })->leftJoin('bids', function($join){
                                $join->on('bids.listing_id', '=', 'listings.id')
                                ->on('bids.id', '=', DB::raw("(select max(id) from bids WHERE bids.listing_id = listings.id)"));

                            })->leftJoin('media', function($join) {
                                $join->on('media.listing_id', '=', 'listings.lot_number')
                                ->where('media.group_order', '=', '1')->groupBy('media.group');
                            });

$listings = $listings->get();

The resulting $listings shows all the search results that I want to appear. Each listing has a specific type (item_type) assigned to them (i.e. Card, Ball, Bat, etc). I'd like to take all those results and group the types so that I can get a unique list of types to display in the menu. I've tried GroupBy on the Collection but that doesn't seem to be working.

Thank You

CodePudding user response:

Use the power of collections

$itemTypes = $listings->pluck('item_type')->unique() 
// if item type is a sub array / relationship then you will need to use dot notation

So we are plucking only the 'item_type' field, removing all duplicates by using the unique method and you should then have a collection of unique item_type's

  • Related