Joins in Eloquent? How?


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', '=', '')

The new approach with the Power Joins package:

Survey::orderByPowerJoins('', $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,


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 👇🏼

Level up your Laravel skills!

Each 2-minute email has real-world advice you can use.