Query Scopes

What are Query Scopes?

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.


Origin

Query Scopes were introduced as part of Eloquent ORM to simplify filtering and reusing common query logic across your application.


Why are they important?

  1. Reusable Query Logic: Encapsulate frequently used filters in a model.
  2. Cleaner Controllers: Reduce the complexity of queries in controllers or services.
  3. Consistency: Apply global constraints automatically across all queries.

Best Practices

  1. Use Local Scopes for Specific Filters: Define local scopes for specific use cases.
  2. Avoid Overusing Global Scopes: Apply global scopes only when necessary.
  3. Combine Scopes: Chain multiple scopes for complex queries.

Example in Action

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.