Global scope in Laravel with example

Here we have some global scope examples in Laravel. Global scopes provide a convenient, easy way to make sure every query for a given model receives certain constraints. In a simple way, we can say that we can add some filter to every query for a specific model.

Answers 1
  • Use of global scope in Laravel

    //app\Scopes\ActiveScope.php
    <?php
    
    namespace App\Scopes;
    
    use Illuminate\Database\Eloquent\Builder;
    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Database\Eloquent\Scope;
    
    class ActiveScope 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', 1);
        }
    }
    
    
    //app\Models\User.php
    <?php
    
    namespace App;
    
    use App\Scopes\ActiveScope;
    use Illuminate\Database\Eloquent\Model;
    
    class User extends Model
    {
       
        protected static function booted()
        {
            static::addGlobalScope(new ActiveScope);
        }
    }
    
    //routes\web.php
    Route::get('/get-active-users-using-global-scope', function(){
        DB::enableQueryLog();
        $users = App\Models\User::all();
        dd(DB::getQueryLog());
    });
    
    0

    Output:

    ^ array:1 [▼
        0 => array:3 [▼
            "query" => "select * from `users` where `is_active` = ?"
            "bindings" => array:1 [▶]
            "time" => 4.57
        ]
    ]
  • Back to code snippet queries related laravel

Related queries helps you to understand and may also used for implementation of current code snippet