Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 819
Abhi Burk Avatar asked Oct 12 '25 17:10

Abhi Burk


1 Answers

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.*');
    });
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!