Thijmen's avatar

Eager loading without scope

Hi folks!

I am running into a problem. I tried to search for similar questions, but no luck :(

In my RouteServiceProvider I am binding a model to routes;

$router->bind('contributionseason', function($value) use ($hashids) {
            $id = $hashids->decode($value)[0];
            return ContributionSeason::with('users.user','users.paymentstatus', 'users.paymentmethod')->findOrFail($id);
        });

This works perfectly. The models are 'eagerly' (not sure if that's a word tho :p) loaded, I can see in the debugbar.

In my User model, I have this piece of code to add a scope:

 static function boot() {
        parent::boot();
        static::addGlobalScope('unsubscribed', function(Builder $builder) {
           $builder->whereNull('unsubscribed_at');
        });
    }

This works also perfectly. Now, I want that when I eager-load my ContributionSeason, that the scope is being removed. I see that this query is executed;

select * from `users` where `users`.`id` in ('25') and `unsubscribed_at` is null

How can I make sure that when I eager load that model, I use something like withoutGlobalScope('unsubscribed')?

Thanks in advance :-)

0 likes
3 replies
acasar's avatar
acasar
Best Answer
Level 13

The easiest way would probably be to create another relation with removed global scope:

public function allUsers()
{
    return $this->hasMany(User::class)->withoutGlobalScope('unsubscribed');
}

Then you can simply call with('allUsers') instead of with('users').

5 likes
Kodandweb's avatar

Old post, but if Googlers like me arrive here, I found this and it's working great:

Model::with([
   "relationship" => function ($query) {
       return $query->withoutGlobalScope(MyScope::class);
   },
]);
2 likes

Please or to participate in this conversation.