Skip to content
Advertisement

Laravel Multiple Sortby Not Working Properly

i have some issues with laravel sortBy ( laravel 5.4 ) .. based on what i read on many websites, it says that for doing multiple sortBy laravel was by using reverse order.. so i try to do that.. but still not working properly..

So here it is.. I have this collection of object…

[{
   'product_id' => 468,
   'name' => 'abc',
   'int_premi' => 10000
   'score' => 1000
   'rates' => 0,
   'views' => 0,
   'promo' => null
},{
   'product_id' => 472,
   'name' => 'bcd',
   'int_premi' => 10000
   'score' => 1000
   'rates' => 0,
   'views' => 0,
   'promo' => 'Some text here'
},{
   'product_id' => 458,
   'name' => 'def',
   'int_premi' => 10000
   'score' => 1000
   'rates' => 0,
   'views' => 0,
   'promo' => 'ABC'
}]

My Goal is to have this objects sorted following this order

score ( asc ) > int_premi ( asc ) > rates ( desc ) > promo ( as boolean ) ( desc ) > views ( desc ) > product_id ( desc )

So i write this code..

$collection->sortByDesc('product_id')->sortByDesc('views')->sortByDesc(function($arr,$k){
                            return !empty($arr->promo);
    })->sortByDesc('rates')->sortBy('int_premi')->sortBy('score')->values()->all()

I’m looking for the result comes with this order

BCD > DEF > ABC

Instead, not following that order..

So is there anyone also facing the same issue with me ? and maybe someone can help me out through this issue ?

Thankyou Very much

Advertisement

Answer

After doing some research.. i found the one is working.. If you are facing the same thing.. this article might help..

https://www.jjanusch.com/2017/05/laravel-collection-macros-adding-a-sortbymuti-function

So my final is exact same thing with this article suggestion, by creating a macro.. like this

if (!Collection::hasMacro('sortByMulti')) {
    /**
     * An extension of the {@see Collection::sortBy()} method that allows for sorting against as many different
     * keys. Uses a combination of {@see Collection::sortBy()} and {@see Collection::groupBy()} to achieve this.
     *
     * @param array $keys An associative array that uses the key to sort by (which accepts dot separated values,
     *                    as {@see Collection::sortBy()} would) and the value is the order (either ASC or DESC)
     */
    Collection::macro('sortByMulti', function (array $keys) {
        $currentIndex = 0;
        $keys = array_map(function ($key, $sort) {
            return ['key' => $key, 'sort' => $sort];
        }, array_keys($keys), $keys);

        $sortBy = function (Collection $collection) use (&$currentIndex, $keys, &$sortBy) {
            if ($currentIndex >= count($keys)) {
                return $collection;
            }

            $key = $keys[$currentIndex]['key'];
            $sort = $keys[$currentIndex]['sort'];
            $sortFunc = $sort === 'DESC' ? 'sortByDesc' : 'sortBy';
            $currentIndex++;
            return $collection->$sortFunc($key)->groupBy($key)->map($sortBy)->ungroup();
        };

        return $sortBy($this);
    });
}

Then you can just using it on your collection like this

$collection->sortByMulti([
    'prop_one'       => 'ASC',
    'prop_two'        => 'ASC',
    etc....
]);

prop_one and prop_two is your collection properties.. Hope this help

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement