aidysproule's avatar

Removing Anonymous Global Scopes when using ->with()

I have a Model with an anonymous global scope applied, see below, how can I remove it when calling the it using with() form another model?

class CandidateProfile extends Model { use HasUlids;

protected static function booted(): void
{
    
    static::addGlobalScope('is_user_owner', function (Builder $builder) {
        $builder->where('user_id', auth()->id());
    });
}

}

Below is how I'm calling it from within a controller, there is a relation setup between the Application and CandidateProfile models.

$applicants = Application::query() ->with(['user.candidate_profile']) ->where('job_id', $job->id) ->get();

0 likes
2 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

To remove an anonymous global scope when using the with() method in Eloquent, you can use the withoutGlobalScope() method. However, since you're dealing with a relationship, you'll need to apply this method within a closure passed to with(). Here's how you can modify your query to remove the is_user_owner global scope from the CandidateProfile model:

$applicants = Application::query()
    ->with(['user.candidate_profile' => function ($query) {
        $query->withoutGlobalScope('is_user_owner');
    }])
    ->where('job_id', $job->id)
    ->get();

In this code, the withoutGlobalScope('is_user_owner') method is used within the closure to remove the specific global scope from the CandidateProfile model when fetching the related data. This allows you to retrieve the CandidateProfile records without the constraint imposed by the is_user_owner global scope.

Please or to participate in this conversation.