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 on Laravel Daily
NativePHP Mobile v4 with SuperNative: Mini-Course
5 lessons
18 min
Marketing for Developers in 2026
7 lessons
52 min
Next.js Basics for Laravel Developers
11 lessons
58 min