'Laravel Model Scope filter relationship

I am working on an app where users can subscribe to services that belong to specific company(ies). I am having an issue to display the user data no the subscription index via eager loading.

I have a global scope setup to show only data for the logged in company user, but when displaying data on subscriptions table its using the logged user's company id which is initiated via the scope.

See Subscription Model Relationships & Model Scope below


    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }


    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope(new CompanyScope);
    }

Company 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)
    {
        if (auth()->check() && auth()->user()->role_id >= 4 && auth()->user()->role_id <= 6) {
            $builder->where('company_id', auth()->user()->company_id);
        }
    }

This is the query that shows in debugbar

select * from `users` where `users`.`id` in (8) and `users`.`company_id` = 2 and `users`.`deleted_at` is null

// Its supposed to read

select * from `users` where `users`.`id` in (8) and `users`.`deleted_at` is null

Its

The data that shows up on the table is below

enter image description here



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source