In this episode, we get hands-on by expanding our Laravel app with a new related model—Addresses—for our users. Here's what we cover:
Building the Address Model: We create an Address model, set up its migration with fields for user_id
and a verified
boolean, and run the migration. We also use factories to quickly generate some test data, so each user gets an address (or more, if you want).
Establishing Relationships: We update the User model to reflect a one-to-many relationship with addresses, so each user can have multiple associated addresses.
Crafting Custom Query Builders: We focus on cleaner, more re-usable queries by building custom query builder classes for both User and Address models. This structure gives us a neat way to encapsulate repeatable logic, similar to scopes, but with extra power (and IDE autocompletion!).
Chaining Custom Query Methods: We write custom methods (like hasVerifiedAddress
on UserBuilder and verified
on AddressBuilder) to easily filter users who have verified emails and verified addresses. We walk through chaining these together efficiently, showing how these custom builders can work together.
Refactoring and Reusability: After showing the basic filtering logic with a closure, we refactor the code to use our new custom query builder methods, making the final queries way more readable and maintainable.
By the end, you’ll see how custom query builders can streamline your codebase, keep things tidy, and promote reusability—making them a fantastic replacement for scattered scopes!