Laravel: sort query results based on field of nested relationship

I have two models with relations as defined below


public function owner()
    return $this->belongsTo(User::class, 'owner_id');


public function company(){
    return $this->belongsTo(Company::class, 'company_id');

company table have ‘title’ field.
what I want is to get all the orders sorted/order by company title. I’ve tried different solution but nothing seems to work. Any help or hint would be appreciated.

Recent solution that I tried is

$query = OrderModel::whereHas('owner', function($q) use ($request){
             // $q->orderBy('owner');
             $q->whereHas('company',function ($q2) use ($request){
                 $q2->orderBy('title',$request->get('orderByDirection') ?? 'asc');

but I am not getting user and company relation in query results. also the result remains same for ‘ASC’ and ‘DESC’ order.

Source: Laravel

Leave a Reply