'Order and Sub Order collection - laravel 7 (Simple)

lets say I have a collection of users Users::all()

I would like to take sort/order it like such Users::all()->sort('created_at', 'DESC')

then I would like to sub order it by an array like [1,5,3,9,4,8] so perhpas a call like this Users::all()->sort('created_at', 'DESC')->sortBy("id", [1,5,3,9,4,8])

Any Advice?

Edit 1

I have found this, is this correct to use?

$ids = collect([1,5,3,9,4,8]);
$users = Users::all()->sort('created_at', 'DESC');
$users = $ids->map(function($id) use($users) {
    return $users->where('cat_id', $id)->first();
});


Solution 1:[1]

I think you could just invoke orderBy() twice.

$ids = [1,5,3,9,4,8];
$users = Users::all()
                ->orderBy('created_at', 'desc')
                ->orderBy($ids)
                ->get();

Does this answer your question?

Solution 2:[2]

You can use whereIn like this probably:

$ids = [1,5,3,9,4,8];

$users = Users::all()
                ->orderBy('created_at', 'desc')
                ->whereIn('cat_id', $ids)
                ->get();

https://laravel.com/docs/9.x/queries#additional-where-clauses

The whereIn method verifies that a given column's value is contained within the given array

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Cas
Solution 2 Ehsan A. Kian