logo
podcast Podcast
get help Get Unstuck

Joins in Eloquent? How?

Sometimes you need a join for performance or sorting by relations. Here's a way to do that without giving up Eloquent.

Joel Clermont
Joel Clermont
2023-10-17

There are two scenarios where I reluctantly break away from using Eloquent, and reach for the Query\Builder SQL join syntax instead:

  1. I need to sort a query by data in a related table.
  2. I need to test for relationship existence and the performance of has() is not good enough.

This approach with SQL joins works, but it's a tradeoff since you lose the nice developer experience of Eloquent collections as a result.

Recently, someone shared with me the Eloquent Power Joins package as a potential solution to these two use-cases without giving up Eloquent.

I'm not using it in production yet, but I gave it a quick try in a local project, and it seems to work well, with relatively little modification to my code.

The old approach with database joins:

Survey::join('clients', 'surveys.client_id', '=', 'clients.id')
    ->select('surveys.*')
    ->orderBy('client_name');

The new approach with the Power Joins package:

Survey::orderByPowerJoins('clients.name', $sort)->get();

As I said before, I haven't used this extensively yet, but it looks promising and I wanted to share it in case you might find it useful.

If you're using this in production already, I'd love to hear from you too.

Here to help,

Joel

P.S. Ash has published a helpful guide to make your Laravel apps "battle ready".

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice you can use.