phplaravellaravel-6global-scope

How do I use Laravel Query Global Scopes


I am implementing Laravel Global Scope as documented here but this seems to be not working for me. Below is my line of code in User.php model

<?php

namespace App;

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

class User extends Model
{
    /**
     * The "booted" method of the model.
     *
     * @return void
     */
    protected static function booted()
    {
        static::addGlobalScope('age', function (Builder $builder) {
            $builder->where('age', '>' , 100);
        });
    }
}

and when I fired User::all() it only gives me user query as select * from users

Please let me know if I am doing something wrong or missing something here...


Solution

  • I finally found what mistake I was making. If someone does the same please check the below details.

    As mentioned in the question I am using Laravel 6.x but I was refering Laravel 7.x which has very much difference. In Laravel 6.x we use

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

    and in Laravel 7.x we use

    protected static function booted(){
       static::addGlobalScope(new BlockedUserScope);
    }