Order Data By Mutator Attribute In Laravel

Accessor and mutator allow you to automatically transform data using custom functions. When you want to order data by mutator attribute in Laravel, the usual Eloquent orderBy() method won’t work directly on mutator values. You need a custom approach to sort the data based on the computed mutator column.

In this article, you will learn how to create a mutator and order data by mutator attribute in Laravel efficiently.

Let’s assume, You have a users table with first_name and last_name. To show the full name easily, you can create a mutator in the User model. This will let you combine first and last name automatically whenever you access the full name attribute.

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

Now we can access the full name like the below example:

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

    $fullName = $user->full_name;

    dd($fullName);
}

But while getting more data or ordering data by full_name, it will throw an error if we use the 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 the desired results:

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

//or

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

Conclusion

In this article, we have sorted data by mutator value. The main difference between the 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.

Here, you can see how to fetch related records efficiently, but to get the most recent related entry, check out our guide on Laravel Eloquent: Get the Latest Row from Relationship.