0

Given the following collection:

$client = Client::all();

//all: [
//    App\Models\Client {
//        #id: 1,
//        name: "Roark",
//    },
//     App\Models\Client {
//        #id: 2,
//        name: "Tanika",
//    },
//    App\Models\Client {
//        #id: 3,
//        name: "Max",
//    },
//     App\Models\Client {
//        #id: 4,
//        name: "Sloane",
//    },
//],

and an array for order priority base on id property:

$priority = [2,3];

I would like to order (sort) the collection and end up with the following order:

    App\Models\Client {
        #id: 2,
        name: "Tanika",
    },
    App\Models\Client {
        #id: 3,
        name: "Max",
    },
    App\Models\Client {
        #id: 1,
        name: "Roark",
    },
    App\Models\Client {
        #id: 4,
        name: "Sloane",
    },

If id is not in priority list, order can remain as pulled from DB.

Ideally I would like to keep the collection as a collection and not use ->toArray()

Any help is greatly appreciated. Thank you!

Roark
  • 1,082
  • 8
  • 9

1 Answers1

1

You can use something like this:

$client = $client->sortBy(
   fn($model) => in_array($model->id, $priority) 
       ? array_search($model->id, $priority) 
       : count($priority) + $model->id
);

using sortBy collection method.

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
  • Thank you very much! Seems to be working a charm! – Roark Oct 13 '21 at 09:25
  • This is a good approach because it accounts for items that are not in the sorting array. I'd recommend adding it as an answer to the dupe target. – miken32 Jan 07 '22 at 21:53