Quick Tip: A Cleaner Way to Apply Custom Eloquent Builders in Laravel
> There are times when the built-in scope methods (scopeActive, scopeLatest, etc.) aren’t enough — especially when your model starts to accumulate lots of complex query logic. A common way to keep things clean is by creating a custom `Eloquent\Builder` class and telling your model to use it, like this: ```php use Illuminate\Database\Eloquent\Builder; class TicketEloquentBuilder extends Builder { // Your query scopes goes here... } ``` Then in your model: ```php use Illuminate\Database\Eloquent\Model; class Ticket extends Model { /** * Override parent Eloquent\Builder class */ public function newEloquentBuilder($query) { return new TicketEloquentBuilder($query); } } ``` It works — but it feels a little messy. You have to override a method, and it isn’t immediately obvious that the model is using a custom builder. ### 📌 The cleaner (and more elegant) way: PHP Attributes Laravel now supports a much more elegant approach using the `UseEloquentBuilder` attribute. No more method overriding. No cluttered model. Just this: ```php use Illuminate\Database\Eloquent\Attributes\UseEloquentBuilder; #[UseEloquentBuilder(TicketEloquentBuilder::class)] class Ticket extends Model { // That's it — no need to override anything 👌🏽 } ``` Much cleaner, more readable, and instantly clear what builder your model is using. ### 🎯 When to use this? This approach shines when: ✔ You’re encapsulating reusable query logic (active, pending, filtered, by role, etc.) ✔ You want a dedicated class for complex query functionality ✔ You value explicit, clean, and attribute-based Laravel features Of course, it’s not required — it’s simply another elegant tool Laravel gives you. Use it when it improves clarity and consistency.