Guntar Guntar - 26 days ago 12
PHP Question

Laravel eloquent orderby two fields with the same name

I have two tables "Companies" and "Properties"
Have a relationship defined in Property class: return $this->belongsTo(Company::class);
I run this eloquent query to get all properties with companies

$properties=Property::with('company')->orderBy('name')->get();


What i can't figure out is how do i orderBy Company.name first and then orderBy property.name? If I do this: orderBy('company.name') I will get an error.
Any help would be highly appreciated.

Answer

You can use join() as:

$properties = Property::join('companies', 'properties.company_id', '=', 'companies.id')
                      ->orderBy('companies.name')
                      ->orderBy('properties.name')
                      ->select('properties.*')
                      ->with('company')
                      ->get();
Comments