PHP

Implement Reusable Global Scopes in Laravel Eloquent

Apply common, consistent query constraints automatically to all queries of a specific Eloquent model using global scopes for unified data filtering.

// Define the Global Scope (App/Scopes/ApprovedScope.php)
namespace App\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Scope;

class ApprovedScope implements Scope
{
    public function apply(Builder $builder, \Illuminate\Database\Eloquent\Model $model)
    {
        $builder->where('approved', true);
    }
}

// Apply to Model (App/Models/Post.php)
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Scopes\ApprovedScope;

class Post extends Model
{
    use HasFactory;

    protected static function boot()
    {
        parent::boot();
        static::addGlobalScope(new ApprovedScope);
    }
}

// Usage Example:
// All queries will include approved posts by default
$approvedPosts = Post::all();

// To retrieve all posts, including unapproved ones:
$allPosts = Post::withoutGlobalScope(ApprovedScope::class)->get();
How it works: Global scopes allow you to enforce common query constraints across all Eloquent queries for a particular model. This example shows how to create an `ApprovedScope` to automatically filter `Post` models to only show approved posts. It also demonstrates how to temporarily remove a global scope using `withoutGlobalScope` when you need to bypass its default behavior.

Need help integrating this into your project?

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

Hire DigitalCodeLabs