Laravel 5: Gotchas – Global Scope

Global Scope with update and select, when using whereHas and related model

When you do any updated (and possibly inserts) you have to call withoutGlobalScope before find():

make private

If you move withoutGlobalScope after find, when you attempt to make aid private, you will make all aids private.

All of them.

Again, I did not investigated why (no time at the moment), but this is how it works.


If you move withoutGlobalScope after find, you will get:

This is because this particular scope filers out all ‘private’ aids.

Bottom line is that, when you release global scope, it must come before using find() method.

Now interesting thing below.

However, when you use Global Scope release (withoutGlobalScope) in select, especially when calling related model and you will use whereHas() method, you need to use it after find() method and after calling related model, or whereHas() method will not work.

See sample code:

So, usually order is not that important in Laravel Query Builder. However, when Global Scopes comes to play, it looks like it becomes important.

Anyway, this is a practical angle.
Tested on L5.6