Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel added data to authenticated user is being applied to every query

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading