In this episode, we dive into the new withAttributes
relationship method in Laravel and see why it's a real game-changer. First, we look at a classic scenario: a User
model with a simple hasMany
relationship to Post
, and a featured
boolean column on each post. Normally, if you want to get only the featured posts, you'd create a scoped relationship or a query using where('featured', true)
, which works well for fetching but does nothing special when you create new posts through the relationship.
But here’s where withAttributes
really shines! Not only does it let you scope the relationship like where
does, but it also automatically pre-fills attributes (like featured: true
) when you create new related models via that relationship. So if you call $user->featuredPosts()->create([...])
, the featured
flag gets set for you - no need to remember to pass it every time.
Throughout the episode, we walk through both methods, test creating posts with and without withAttributes
, and see how Laravel handles these cases behind the scenes. By the end, you'll see just how valuable withAttributes
can be for keeping your code clean and your intentions clear when dealing with scoped relationships and default values.
If you often define similar relationship helpers, this new approach will definitely make your life easier!