Skip to main content
Quick Tip

Ordering by an Eloquent Accessor

Ordering by an Eloquent Accessor! Yes, that's doable. Instead of ordering by the accessor on the DB level, we order by the accessor on the returned Collection.

class User extends Model
{
// ...
protected $appends = ['full_name'];
 
// Since Laravel 9
protected function full_name(): Attribute
{
return Attribute::make(
get: fn ($value, $attributes) => $attributes['first_name'] . ' ' . $attributes['last_name'];),
);
}
 
// Laravel 8 and lower
public function getFullNameAttribute()
{
return $this->attribute['first_name'] . ' ' . $this->attributes['last_name'];
}
// ..
}
class UserController extends Controller
{
// ..
public function index()
{
$users = User::all();
 
// order by full_name desc
$users->sortByDesc('full_name');
 
// or
 
// order by full_name asc
$users->sortBy('full_name');
 
// ..
}
// ..
}

sortByDesc() and sortBy() are methods on the Collection

Tip given by @bhaidar

Enjoyed This Tip?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Recent Courses

Laravel Modules and DDD

16 lessons
1 h 59 min

Laravel 12 For Beginners: Your First Project

15 lessons
1 h 32 min

Filament 4 From Scratch

28 lessons
2 h 25 min

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.