There are two scenarios where I reluctantly break away from using Eloquent, and reach for the
Query\Builder SQL join syntax instead:
- I need to sort a query by data in a related table.
- 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:
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".