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.

1class User extends Model
2{
3 // ...
4 protected $appends = ['full_name'];
5 
6 public function getFullNameAttribute()
7 {
8 return $this->attribute['first_name'] . ' ' . $this->attributes['last_name'];
9 }
10 // ..
11}
1class UserController extends Controller
2{
3 // ..
4 public function index()
5 {
6 $users = User::all();
7 
8 // order by full_name desc
9 $users->sortByDesc('full_name');
10 
11 // or
12 
13 // order by full_name asc
14 $users->sortBy('full_name');
15 
16 // ..
17 }
18 // ..
19}

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:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord