Using Global Scopes With DB Facade

Posted 1 week ago by danny620

Good Morning All,

I have a simple query below that reports on the total number of installations taken place month on month


public function totalInstallationsMonthOnMonth()
    {
        return Cache::remember($this->userCacheSignature() . 'totalInstallationsMonthOnMonth', 120, function () {

            $data = [];

            $data['labels'] = ['Total Installations Registered'];
            $data['data'] = \DB::table('installations')
                                        ->select(DB::raw('YEAR(created_at) year, MONTHNAME(created_at) monthname, MONTH(created_at) month'), \DB::raw('count(*) as total'))
                                        ->groupBy('month')
                                        ->orderBy('month')
                                        ->pluck('total', 'monthname')
                                        ->all();
            return $data;

        });
    }

I want to show admins all the data, but I want to use a global scope that I've created that determines the role that you are and if your an installer it will add "installer_id" where clause. It works just fine when I'm using it not with the db facade.


<?php

namespace App\Traits;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;

trait FilterByUserType
{
    protected static $tenantColumn = 'installed_by_id';
    protected static $ignoreRoles = ['super_admin', 'admin', 'staff'];

    protected static function bootFilterByUserType()
    {
        if (!app()->runningInConsole() && !Auth::guest()) {

            if(Auth::user()->hasAnyRole(self::$ignoreRoles)) return;

            static::creating(function ($model) {
                $model->{self::$tenantColumn} = Auth::User()->typeable_id;
            });

            static::addGlobalScope(self::$tenantColumn, function (Builder $builder) {

                if(Auth::User()->typeable_type == 'App\Installer') {
                    $builder->where('installed_by_id', Auth::User()->typeable_id);
                }
                
                if(Auth::User()->typeable_type == 'App\CertificationBody') {
                    $builder->where('certification_body_id', Auth::User()->typeable_id);
                }

                if(Auth::User()->typeable_type == 'App\ConsumerCode') {
                    $builder->where('consumer_code_id', Auth::User()->typeable_id);
                }

                if(Auth::User()->typeable_type == 'App\IbgProvider') {
                    $builder->where('ibg_provider_id', Auth::User()->typeable_id);
                }

                if(Auth::User()->typeable_type == 'App\Manufacturer') {
                    $builder->where('manufacturer_id', Auth::User()->typeable_id);
                }
                    
            });
        }
    }
}


Please sign in or create an account to participate in this conversation.