PHP

Applying Global Scopes for Automated Query Filtering

Implement Laravel Eloquent global scopes to automatically apply common query constraints like status or tenant filtering across multiple models, simplifying your codebase and ensuring consistency.

<?php

namespace App\Scopes;

use Illuminate\Database\Eloquent\Builder;

use Illuminate\Database\Eloquent\Model;

use Illuminate\Database\Eloquent\Scope;



class ActiveUserScope implements Scope

{

    /**

     * Apply the scope to a given Eloquent query builder.

     *

     * @param  \Illuminate\Database\Eloquent\Builder  $builder

     * @param  \Illuminate\Database\Eloquent\Model  $model

     * @return void

     */

    public function apply(Builder $builder, Model $model)

    {

        $builder->where('is_active', true);

    }

}



// In your User Model (App\Models\User.php)

namespace App\Models;



use App\Scopes\ActiveUserScope;

use Illuminate\Database\Eloquent\Model;



class User extends Model

{

    /**

     * The "booted" method of the model.

     *

     * @return void

     */

    protected static function booted()

    {

        static::addGlobalScope(new ActiveUserScope);

    }



    // To retrieve all users, including inactive ones, you can remove the global scope:

    // User::withoutGlobalScope(ActiveUserScope::class)->get();

}



// Usage elsewhere in your application:

// $activeUsers = User::all(); // Automatically includes 'where is_active = true'

// $specificActiveUser = User::find(1); // Also applies the scope
How it works: Global scopes allow you to add constraints to all queries for a given model. This snippet demonstrates creating an `ActiveUserScope` class that filters users to only include those where `is_active` is `true`. By adding this scope in the `booted` method of the `User` model, every subsequent query on the `User` model will automatically include the `where('is_active', true)` condition, promoting consistent data retrieval. You can temporarily remove a global scope using `withoutGlobalScope` when needed.

Need help integrating this into your project?

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

Hire DigitalCodeLabs