JillzTom's avatar

Remove global scope on specific query

I've a User and Post model. Both of them has a Global scope to get only published or unblocked user.

Now, I need to get the list of all posts even if the author is blocked.

This is the query that I used.

$posts = Post::withoutGlobalScopes()->paginate(10);

But since I've the author relationship with it appended, I get the author as null (due to the global scope if the user is blocked).

How can I remove the global scope of the author in the above query and get all posts (published/unpublished) along with the author (blocked/unblocked).

How can I do this?

0 likes
5 replies
AhimbisibweRoland's avatar

Eager load the relationship forexample

$posts = Post::withoutGlobalScopes()->with("author")->paginate(10);

1 like
JillzTom's avatar

Actually, this only removes the scope from Post model and not from the Author model.

SuryaVL's avatar

For those arriving here from google: the solution would be to set up a new relation

public fuction authorNS(): BelongsTo
{
	return $this->blongsTo(Author::class)->withoutGlobalScopes();
}

$posts = Post::withoutGlobalScopes()->with("authorNS")->paginate(10);
1 like
rawfan's avatar

I just came across this looking for a solution. You can actually remove global scopes from relations using closures (also from relationship existence queries):

To remove global scopes from a models relation, you need to eager load the relation and modify the query of the eager load.

Model::with([
   'relation' => fn ($query) => $query->withoutGlobalScopes()
]);

If you use Model::has('relation') to query for the existence of relationships, you can use whereHas instead, to remove global scopes:

Model::whereHas(
   'relation', fn ($query) => $query->withoutGlobalScopes()
);
3 likes
34ML's avatar
            $model->load(['relation' => function ($query) {
                $query->withoutGlobalScopes([HideScope::class]);
            }]);

Please or to participate in this conversation.