I’m able to add more data to the authenticated user by using the Laravel Global Scopes what I didn’t know is that this forces the data in every relationship with the model User.
My user class is something like this:
class User extends Authenticatable
{
protected static function booted()
{
static::addGlobalScope('subscription', function (Builder $builder)
{
$builder->with('subscription.lastpayment');
$builder->with('tickets');
});
}
}
Which translates to being able to access auth()->user()->subscription, auth()->user()->subscription->lastpayment and auth()->user()->tickets.
But now if I use a model that has a relationship with the user model, such as:
$tickets = \App\Models\Tickets::with('user')
->with('lastmessage')
->with('lastmessage.user')
->where('subscription_id', auth()->user()->subscription_id)
->get();
Both with('user') and with('lastmessage.user') are running the global scope and querying subscriptions, lastpayment & tickets tables.
How can I avoid this? This is performing multiple queries unnecessarily.
>Solution :
Did you try using withoutGlobalScope() ?
example
$tickets = Tickets::withoutGlobalScope('subscription')
->with('user')
->with('lastmessage')
->with('lastmessage.user')
->where('subscription_id', auth()->user()->subscription_id)
->get();
To completely disable specific queries you can pass empty like this
Tickets::withoutGlobalScopes()->...
Edit 01
try with using without()
$tickets = Tickets::with(['user' => function ($query) {
$query->without('subscription', 'tickets');
}])
->with(['lastmessage.user' => function ($query) {
$query->without('subscription', 'tickets');
}])
->where('subscription_id', auth()->user()->subscription_id)
->get();