Query Scopes in Laravel are methods that allow you to encapsulate common query constraints within Eloquent models, making queries reusable and improving code readability. Scopes can be global or local.
Query Scopes were introduced as part of Eloquent ORM to simplify filtering and reusing common query logic across your application.
Define a local scope in the User
model:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function scopeActive($query)
{
return $query->where('status', 'active');
}
}
Use the scope in a query:
$activeUsers = User::active()->get();
For global scopes, create a class:
php artisan make:scope ActiveScope
In the ActiveScope
class:
namespace App\Scopes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
class ActiveScope implements Scope
{
public function apply(Builder $builder, Model $model)
{
$builder->where('status', 'active');
}
}
Apply the global scope in the model:
protected static function booted()
{
static::addGlobalScope(new ActiveScope);
}
This ensures that only active users are queried by default.