2

I have database table with different roles and I need collection where items with role owner will be last. Here is database example:

ID Role
1 admin
2 user
3 user
4 owner
5 user

How can I sort collection with those data to get item with role owner as last? I could only think of sorting it alphabetically, saving to some variable and deleting the record with the owner role from the collection, and then pasting it into the collection as last. But it seems unnecessarily complicated to me, isn't there an easier way?

The reason why I need this is because I need remove all selected users and to be sure that user/owner is the last one.

Jaroslav Klimčík
  • 4,548
  • 12
  • 39
  • 58

2 Answers2

7

You Can Use Conditional rendering. For That you need to use DB::raw Example:

Model::select('id', 'role')
  ->orderBy(DB::raw('role = "owner"'), 'ASC');

Or you can use shortcut orderByRaw

Model::select('id', 'role')->orderByRaw("role = 'owner' ASC");

It will place owners At the end.

Check Fiddle here: http://sqlfiddle.com/#!9/9d2b64/2

Malkhazi Dartsmelidze
  • 4,783
  • 4
  • 16
  • 40
1

For eloquent, you can use sortBy() method with array_search() :

$collection = Model::get();

$data = $collection->sortBy(function($item){
    return array_search($item->role, ['admin', 'user', 'owner']);
});
STA
  • 30,729
  • 8
  • 45
  • 59
  • What if Model has hundreds of records? First you select and then sort? I think this is not good solution. – Malkhazi Dartsmelidze Jul 15 '21 at 12:42
  • @Malkhazi I think you need to ask this on laravel's developer https://laravel.com/docs/8.x/collections#method-sortby – STA Jul 15 '21 at 12:45
  • It's clear that `sortBy` method exists and I use it a lot. But it's not recomended to use in this case, when you can sort data using `SQL`. Collections are heavy, especially when you are blindly using `get` or `all` method. – Malkhazi Dartsmelidze Jul 15 '21 at 12:50
  • Result will be right but I agree with @Malkhazi - in my case I can have thousands of records and fetching all records could be pain but I admit that I didn't wrote it into description. – Jaroslav Klimčík Jul 15 '21 at 13:00