Laravel scopes for reusable query logic

11120
0

Query scopes encapsulate common query constraints into reusable methods on models. Local scopes prefix methods with scope and accept a query builder plus additional parameters. I chain scopes fluently—Post::published()->featured()->get(). Global scopes apply to all queries automatically, useful for soft deletes or multi-tenancy. Anonymous global scopes use closures in the booted() method. Scopes keep controllers clean by moving query logic to models where it belongs. Dynamic scopes accept parameters for flexible filtering. The combination of local and global scopes creates a powerful query API specific to each model. This pattern is fundamental to readable, maintainable Eloquent queries.