laravel-query-builders
Installation
SKILL.md
Laravel Query Builders
When a model needs query constraints that more than one caller uses, they go on a custom builder for that model: OrderBuilder extends Builder, one method per constraint, each returning self so they chain. Local scopes are never used. Every query is started with Model::query(), so the chain is typed as the model's builder from its first call.
Rules
- Start every query with
Model::query().Order::query()->wherePaid()->get(), neverOrder::wherePaid()orOrder::where(...). Every chain then reads the same way and starts from a real method that returns the model's builder, rather than a static call forwarded through__callStaticand__call. - A builder, never a local scope. No
scopeWherePaid(). A builder method is a plain, typed method that autocompletes and can call the other constraints on the builder. - Create a builder when a model needs a reusable constraint. Not for every model, and never empty "for later". A one-off
where()stays inline in the action or query class that uses it. - One builder per model, named
{Model}Builder. It lives inBuilders/beside the other classes of its kind (see laravel-architecture). - Register it with
#[UseEloquentBuilder(OrderBuilder::class)]on the model (Laravel 12.19+). Below 12.19, overridenewEloquentBuilder(), as shown after the example. - Name by what the method does.
where*adds a constraint:wherePaid(),whereCustomer(),whereHasBackorderedLines().with*loads relations or adds a computed column:withRelations(),withLowestBid(). - Methods compose. A constraint built from others calls them (
whereOverdue()callswherePaid()), so each rule is written once. - Type parameters as the domain types they are. Models, enums, contracts. A related model goes through
whereBelongsTo($customer); never acceptCustomer|intand branch oninstanceof. - Dates are
CarbonInterface, neverCarbon. The app runs onCarbonImmutable(see laravel-providers), so aCarbonparameter throws aTypeErrorwhen passednow(). - Type every query closure. A
whereHas()closure receives the related model's builder,function (OrderLineBuilder $query): void; a nestedwhere()closure receives this one,function (OrderBuilder $query): void. Eager-load constraints receive the relation itself: type them as what they are,HasMany; it forwards builder calls. The type is what makes the builder's methods autocomplete inside the closure. withRelations()is the model's eager-load set. When a model is usually loaded with the same relations, they're listed once, inwithRelations(), and reused by query classes, route binding and other builders' eager-load constraints. One name on every builder; neverwithRelated(),withAll()orwithFullRelations().