Home > Enterprise >  Order collection by property value being present in another array or collection
Order collection by property value being present in another array or collection

Time:10-14

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!

CodePudding user response:

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.

  • Related