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(), never Order::wherePaid() or Order::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 __callStatic and __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 in Builders/ 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, override newEloquentBuilder(), 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() calls wherePaid()), 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 accept Customer|int and branch on instanceof.
  • Dates are CarbonInterface, never Carbon. The app runs on CarbonImmutable (see laravel-providers), so a Carbon parameter throws a TypeError when passed now().
  • Type every query closure. A whereHas() closure receives the related model's builder, function (OrderLineBuilder $query): void; a nested where() 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, in withRelations(), and reused by query classes, route binding and other builders' eager-load constraints. One name on every builder; never withRelated(), withAll() or withFullRelations().

Example

Installs
58
GitHub Stars
15
First Seen
Mar 27, 2026