In this episode, we look at how you can add modifiers—like scopes or constraints—directly to Eloquent relationships in your model. We kick things off by talking about a scenario where we want all posts to be shown in the 'latest first' order throughout the app, and how manually adding latest()
or orderBy
everywhere is repetitive. Instead, you can attach these sorts of modifiers right to the relationship definition in your model.
While this is pretty neat and can help dry up your code, I point out a few things to watch out for. For example, if you ever need posts in another order later, having the scope right on the relationship could get in your way and need to be undone. So, it's handy for consistency, but you have to be sure it's what you want across the board.
Next, I demo how to use these modifiers directly in the relationship method, and show the practical benefit: you don't have to repeat sorting logic in your controllers or routes—just call $user->posts
and you're set. We then take it a step further by introducing custom relationships. For example, you could have a standard posts
relationship, and another like latestPosts
that always returns posts in descending order. This way, you can reuse the base relationship or apply constraints as needed, keeping things nice and clean.
Overall, this episode is all about making your relationships more flexible and expressive, saving you from duplicating logic, and making your code easier to read and maintain!