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

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 68 courses (1183 lessons, total 43 h 18 min)
  • 90 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent New Courses