How to order data by accessor and mutator in laravel

Accessor and mutator help us to change data by custom functionally automatically. While working with a mutator sometimes we need to order or sort data by mutator column. But the Eloquent model's orderBy() method doesn't work with mutator value. So how to order data by mutator column value?

In this article, we will create a mutator and sort data by mutator. Let's start by creating a mutator.

Let's assume, you have a user table which contains two columns first_name and last_name and you want to display the full name sometimes. As you know, we can achieve this functionality using a mutator so open the User model and add the below code into it:

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

Now we can access the full name like below example:

function getUser($id)
    $user = User::find($id);

    $fullName = $user->full_name;


But while get more data or ordering data by full_name, it will throw an error if we use orderBy() Eloquent method :

$users = User::orderBy('full_name')->get(); // Will show error

The orderBy() will not work to order data by mutator. You need to use sorting functionality to get desired results:

$users = User::get()->sortBy('full_name');


$users = User::get()->sortByDesc('full_name');

Here, you can see two queries that fetch the same data the first one will get data in ascending order while the second one will sort data into reverse order.

The sortBy() method is a collection method that can work on any other collection object while the orderBy() method is an eloquent method that will perform only on the database as a query.


In this article, we have sorted data by mutator value. The main difference between orderBy() and sortBy() methods is that the orderBy() method sorts data while fetching from a database while sortBy() method will perform sorting after fetching data from a database. So while calling the sortBy column, we will have full name value in our collection.