Jaroslav Klimčík
Jaroslav Klimčík

Reputation: 4808

Laravel Collection - put specific item on last position

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.

Upvotes: 2

Views: 1643

Answers (2)

Malkhazi Dartsmelidze
Malkhazi Dartsmelidze

Reputation: 4992

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

Upvotes: 8

STA
STA

Reputation: 34678

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

Upvotes: 1

Related Questions