mySun
mySun

Reputation: 1696

How to use sortBy after groupBy in collect in Laravel 5.3?

I need after get query from sql with Eloquent, create groupBy('date') and sortBy('price') with collect in Laravel 5.3.

In IndexController:

$flights = Flights::GetFlights($fromCity, $toCity, $fromDate);

$collection = collect($flights);

$sortFlight = $collection->groupBy('date')->sortBy('price');

In Model:

public function scopeGetFlights($query, $fromCity, $toCity, $fromDate)
{
    // Between dates
    $beforeDate = date('Y-m-d', strtotime($fromDate . '- 10 days'));
    $afterDate = date('Y-m-d', strtotime($fromDate . '+ 10 days'));

    $join = $query
        -> join('airlines', 'airlines.pana', 'flights.airline')
        -> where('flights.from_city', $fromCity)
        -> where('flights.to_city', $toCity)
        -> whereBetween('flights.date', [$beforeDate, $afterDate])
        -> get([
                 'flights.*',
                 'airlines.pana as pana',
                 'airlines.name as airlineName'
              ]);
    return $join;
}

Then Print_r($sortFlight), After print groupBy('date') is works but sortBy('price') does not work!!!!

Where is my problem?

Upvotes: 2

Views: 8767

Answers (3)

Gayan
Gayan

Reputation: 3704

From the doc

The sortBy method sorts the collection by the given key. The sorted collection keeps the original array keys, so in this example we'll use the values method to reset the keys to consecutively numbered indexes:

So after doing groupBy() do as follows.

$sorted = $collection->groupBy('date')->sortBy('price');
$sorted->values()->all();

Upvotes: 2

subdesign
subdesign

Reputation: 190

My solution for sorting values in a grouped collection in Laravel

$sponsors = Sponsor::with('sponsor_level')->whereStatus(1)->get();

// grouped by sponsor level name
$grouped = $sponsors->sortBy('sponsor_level.order')->groupBy(function($item, $key){
    return $item->sponsor_level->name;
});

// finally sorted by sponsor name inside the group
return $grouped->map(function($item, $key){
    return $item->sortBy('name');
});

You can chain these of course, I separated for better readability.

Upvotes: 5

Vikash
Vikash

Reputation: 3551

Try this single line

$sortFlight = $collection->groupBy('date')->sortBy('price')->values()->all();

Upvotes: 2

Related Questions