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.
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