CharlesK's avatar

Laravel orderby uses

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.

0 likes
3 replies
MikeMacDowell's avatar

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();
});
5 likes
tisuchi's avatar
tisuchi
Best Answer
Level 70

@charlesk

You have a few options here-

  • Create a view in your database, which has the column fullName. Then change your model to use the view.
  • Create a computed column fullName so that on insert if will use the values given from firstName and lastName.
  • Use Laravel's Collection class. This class provides a sortBy method in which you can use an attribute.

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

7 likes

Please or to participate in this conversation.