PHP

Create Reusable Local Scopes in Laravel Eloquent

Discover how to define local scopes in Laravel Eloquent to encapsulate common query constraints, making your code more readable and reusable across different parts of your application.

// app/Models/User.php
namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    // A simple local scope
    public function scopeActive(Builder $query)
    {
        return $query->where('is_active', true);
    }

    // A local scope with parameters
    public function scopeOfType(Builder $query, string $type)
    {
        return $query->where('type', $type);
    }

    // Another example scope
    public function scopeCreatedLastWeek(Builder $query)
    {
        return $query->where('created_at', '>=', now()->subWeek());
    }
}

// Usage example
$activeUsers = User::active()->get();

$adminUsers = User::ofType('admin')->get();

$activeAdminUsersCreatedLastWeek = User::active()->ofType('admin')->createdLastWeek()->get();
How it works: Local scopes allow you to define common sets of query constraints that you can easily re-apply on a model's query builder chain. You define them by prefixing a method name with `scope` (e.g., `scopeActive`). These methods receive the query builder instance as their first argument, allowing you to chain additional `where` clauses or other query methods. They promote code reusability and make complex queries more readable.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs