mailwal

Eloquent is great, but don't forget about joins

Joel Clermont
Logo

The power of the humble SQL join

Eloquent is incredibly powerful. We can get so much done that we might even forget about simple SQL concepts like using a join to bring in data from another table.

Here's a scenario

You're fetching a collection of Survey models using Eloquent, but you want to sort the results by a field on a related table. Let's say the name field on the Client table.

Eloquent does not provide a way to order the query by the value of a field in a related model.

SQL joins to the rescue!

In the code sample, we're using join to bring in the other table. But once you do this, you no longer automatically get all the properties from Eloquent, so we need to pair it with the select method on the next line. Now, we can use the normal orderBy method, but with that related table's field. Mission accomplished!

For most queries, Eloquent has you covered, but every once in a while you need to use methods on the underlying Database\Query\Builder class with fundamental SQL concepts. Don't forget those fundamentals!

Here to help,

Joel


You received this email because you signed up at masteringlaravel.io. Thanks!

Or click here to update your email address.