3

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...

Abhi Burk
  • 2,003
  • 1
  • 14
  • 21

3 Answers3

4

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);
}
Abhi Burk
  • 2,003
  • 1
  • 14
  • 21
  • Yeah and I was trying the latest one on Laravel 6.x – Abhi Burk Jul 19 '20 at 14:16
  • Why? Where is it documented? I've been struggling to find the right way how to do this in L8. Boot or booted? – Jakub Feb 07 '21 at 15:25
  • L 6.x has `boot` - https://laravel.com/docs/6.x/eloquent#global-scopes and L 7.x or > has `booted` - https://laravel.com/docs/7.x/eloquent#global-scopes – Abhi Burk Feb 15 '21 at 12:17
2

in Laravel 8.x we use

protected static function booted()
{
    static::addGlobalScope(function ($query) {
        $query
            ->join('model_has_roles', function ($join) {
                $join->on('model_id', '=', 'users.id')
                    ->where('model_type', '=', 'App\Models\User');
            })
            ->join('roles', function ($join) {
                $join->on('role_id', '=', 'roles.id')
                    ->where('roles.name', '=', 'visitor');
            })
            ->select('users.*');
    });
}
1

In Laravel 8's Illuminate\Database\Eloquent\Model,
I can see 3 calls, wihtout anything in between, like:

static::booting();
static::boot();
static::booted();

Meaning placing our logic at end of boot() method is same for all versions.

Hence, no matter what Laravel version, try something like:

protected static function boot(){
    parent::boot();
    static::addGlobalScope(new BlockedUserScope);
}
Top-Master
  • 7,611
  • 5
  • 39
  • 71