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 // or12 13 // order by full_name asc14 $users->sortBy('full_name');15 16 // ..17 }18 // ..19}
sortByDesc
and sortBy
are methods on the Collection
Tip given by @bhaidar