Not from the database, but if you have a collection of users you can use the collection method sortBy
$sorted = $collection->sortBy(function ($user, $key) {
return $user->fullName();
});
How can I use orderBy to order by a model's method?
Consider the model User and the method
public function fullName() {
return $this->firstName . $this->lastName;
}
I want to do something like orderBy('fullName'). Is this possible? I know I can make equivalent code using Query Builder, but I want to keep my Model methods as they are.
You have a few options here-
If you go with option 2, first define an attribute:
public function getFullNameAttribute()
{
return $this->firstName . $this->lastName;
}
Then using Laravel's Collection:
$items = Model::all()->sortBy('FullName');
Please take a note that the default option for sortBy is ascending, so if you wish to sort descending:
$items = Model::all()->sortByDesc('FullName');
Check more: https://laravel.com/docs/master/eloquent-mutators#defining-an-accessor
Please or to participate in this conversation.