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
Roles and Permissions in Laravel 13
14 lessons
57 min
Testing in Laravel 13 For Beginners
26 lessons
1 h 41 min read
NativePHP v3: Create Mobile Apps with Laravel
10 lessons
1 h 02 min