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