You mean ->withCount(table)->orderBy(table_count)?
Hard to answer without a specific example.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
On the collection, I can do the sorting with a closure like this
$collection = collect([
['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
['name' => 'Chair', 'colors' => ['Black']],
['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
]);
$sorted = $collection->sortBy(function (array $product, int $key) {
return count($product['colors']);
});
$sorted->values()->all();
How can I do the same with the Eloquent query builder?
You can use a computed column in the database to get the results direct from the database sorted with the owner first
$taskList = $taskList->select('*')
->selectRaw('(case when created_by_id = ? then 0 else 1 end) as owner', [auth()->user()->id])
->orderBy('owner')
->paginate($items ?? 10);
Sets a new column on the query result of owner and then orders by that column.
Please or to participate in this conversation.