Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

laramit's avatar

Order by and left join

I've been using the following code to pull out a list of products and their related companies:

$products = Product::join('companies', 'companies.id', '=', 'products.company_id')
->orderBy('companies.name', 'asc')
->select('products.*');

Which works OK but some products don't have a related company so were being excluded by the inner join. I therefore changed it to a leftJoin which does pull out all the products however this then seems to ignore the orderBy.

It seems to be ordering by the products rather than the company name when I use the leftJoin this way. Can't really understand why it would ignore the orderBy?

0 likes
6 replies
InaniELHoussain's avatar

by the way, you have to select it first(the companie name) what about

$products = Product::join('companies', 'companies.id', '=', 'products.company_id')
->orderBy('companies.name', 'asc')
->select('products.*, companies.name');
1 like
laramit's avatar

Thanks,

Tried that but still won't order the results by company name. Even tried removing the select completely (hoping we then get all columns from both tables).

Wondering if I'm going to need to use some raw SQL!

InaniELHoussain's avatar

what about this

$products = Product::join('companies', 'companies.id', '=', 'products.company_id')
->orderBy(DB::raw("companies.name"),'asc') 
->select('products.*, companies.name');
laramit's avatar

Thanks again.

Weird one - repaired and optimised the MySQL database and it now works. Wonder if the table indexes were corrupt?

laramit's avatar

Sure is! - those are hours of my life I'll never get back!

Appreciate your help anyway :-)

1 like

Please or to participate in this conversation.