In this episode, we're taking things a step further by looking at how to select only the columns we really need—not just on our main models, but also on their related models. We'll use the example of a User
model related to something like Posts
, but the same idea applies to any relationship.
Even if your user table isn't massive, it's good practice to only fetch the data you actually use. This pays off big if you have related tables that could be huge. We'll walk through how to use Laravel's eager loading with a custom query builder closure, so you can tell Laravel exactly which columns to grab from the related models. You'll see this in action and get a sense for when it really makes a difference in performance.
We also cover a convenient shortcut: instead of passing a closure, you can use the colon syntax in your relationship to specify which columns you want, making your code neater and easier to read. Quick reminder—don't forget to include the necessary foreign keys, or things won't join up properly!
So if you want your Eloquent queries to be lean and efficient—especially when working with lots of data across relationships—this episode will show you exactly how to do it.