Laravel Collection - put specific item on last position

Viewed 457

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.

2 Answers

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 Use shorthand:

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

It will place owners At the end.

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

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']);
});
Related