I have seen global scopes being applied by default in a lot of projects at my previous company and I always wondered how it makes your code base cleaner, especially when the currently logged-in user is used in the scope.
But what if you want to use Transaction in a different context, such as a command or a job, where, for example, you want to send a user his/her last 10 transactions in an email. At that point there's no authentication available and your query will return an empty result. This means that as a developer I need to be aware of this global scope being applied. Also, in every context where auth is not available or where I just want to query Transactions for something completely different, I have to opt-out using 'withoutGlobalScope()', which feels so counter intuitive :/
I feel that global scopes (applied by default) very often are being used as some kind of "security mechanism" to not accidentally display data not intended for the logged-in user. But why not define a local scope taking a User as an argument, so it can be reused in every context and then thoroughly test, for the same reason you mention in the last section?
I have never felt the need to use global scopes applied by default, which is obviously just my humble opinion :) A scenario in which global scopes are the way to go, I feel, is a tenant based application, where you could have a global scope for different tenants. But even then, if you take a look at some of the available Laravel tenancy packages, you'll see that the scope is not applied by default, but only when a tenant route is hit using middleware to apply it.
Just my respectful two cents :)
Thank you for your contribution Maarten Troonbeeckx!
I agree that you need to figure out if a global scope is a smart approach in every specific use case. That is what this article is all about, actually.
For security, I really understand why global scopes are used. In larger teams, the authentication cannot be overseen in a PR now, so we're secure by default. In a healthy development process (write tests, etc.) the developer sees that he needs to use the "withoutGlobalScopes" during development, so this should not be a problem at all. But this triggers the developer to think about the security, and that is a good thing. In a PR, the reviewer will also be triggered when he sees the "withoutGlobalScopes" and makes this an area of interest to focus on in the review.
But of course, every specific use case has different needs and every team has its own preferences.