Eloquent: How to Order Results by Mutator Attribute?

Recently I’ve encountered a situation and want to share a quick solution with you guys. Laravel has quite an awesome feature of Mutators – you can define extra fields in your Eloquent models that are dynamically calculated. But orderBy doesn’t work with them, so what can we do?

First, I will remind you how it works. Imagine, you have Client.php model and fields first_name and last_name. You can define full_name attribute like this:

function getFullNameAttribute()
  return $this->attributes['first_name'] . ' ' . $this->attributes['last_name'];

And then, when doing $clients = Client::all();, you can use it like this:

@foreach ($clients as $client)
  {{ $client->full_name }}

Quite convenient, right?
But what if you want to order results by full_name? Simple orderBy throws an error.

$clients = Client::orderBy('full_name')->get(); // doesn't work

The solution is quite simple. We need to order the results after we get them.

$clients = Client::get()->sortBy('full_name'); // works!

Notice that the function name is different – it’s not orderBy, it’s sortBy.
Also, there’s sortByDesc():

$clients = Client::get()->sortByDesc('full_name');

The thing is that sortBy function works with Eloquent results which is a collection. You can read more about sortBy and other Collection functions (plenty of them!) here in the official documentation.

Like our articles?
Check out our Laravel online courses!


  1. Thanks for pointing this out, might come handy.

    This is a bit limited thought since if you paginate your results ordering will work only on the current page and not in all results.

    Another dirty solution might be to reconstruct your Attribute in you select so you can actually sort by it!

    So you can do do Client::selectRaw(“client.*, concat(client.name, ‘ ‘, client.surname) as full_name”)->orderBy(‘full_name’)->get();

    • Yeah, good point, default Laravel pagination wouldn’t work this way. And yes, for big amounts of data sorting afterwards is a pretty slow solution. Your dirty hack with raw queries could be possible the most effective one, thanks!

  2. Just to make it completely obvious to everybody. This WILL have a performance impact if you have even ust low thousands of records. Millions of records will introduce notable lag.

    By doing get() before, you get ALL rows, and sort them in RAM in PHP.

    The same goes for people who run ->get()->count() to get the count. Always use ->count() directly on the Eloquent model.

    I know this is the case here, but it should be stated more clearly, that this should be a last-ditch “hacky” option, and even if you expect to have just 1000 records, you should consider doing it “the right way”.


Please enter your comment!
Please enter your name here