News

Local Model Scopes in Laravel with the Scope Attribute

Published
Local Model Scopes in Laravel with the Scope Attribute image

Release updates

Never miss a Laravel release

Get an email whenever a new Laravel release lands.

When I wrote about Laravel 12.4, I missed a completely new way to write local scopes in Eloquent models 😅. For as long as I can remember, you can define query scopes within a model by prefixing a public method with scope:

public function scopePopular(Builder $query): void
{
$query->where('votes', '>', 100);
}
 
User::popular()->orderBy('created_at', 'DESC')->get();

While Laravel 12 applications will still support the scope* prefixed methods to define a model scope, the new #[Scope] attribute can be used, and it keeps your method name as intended:

use Illuminate\Database\Eloquent\Attributes\Scope;
 
#[Scope]
protected function popular(Builder $query): void
{
$query->where('votes', '>', 100);
}

You can learn more about scopes and getting started with Eloquent in the Laravel documentation. This feature was merged in Laravel v12.4 - check out pull request #54450 for discussion and implementation details.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Sponsored

serpapi logo
SerpApi

The Web Search API for Your LLM and AI Applications

Visit SerpApi

The latest

View all →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article