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 }}
@endforeach
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.
No comments or questions yet...