@martin.sinansky@gmail.com It sounds like your isAdmin() check may be making a db call every-time the model is referenced. Anytime you see the same data call being made and you cant address it as a simple N+1 fix, it could be useful to reach for Cache::remember() to store the data retrieval in memory so the app is only making the call once. For things like permissions, this can be made fairly short-term as you'll want permissions to properly reflect when updated. Alternately you can store them in cache forever and just replace or bust them once they are updated.
Too many calls to policy ???
Hello guys,
I would like to ask for a bit of an advice from someone more experienced with app optimization. One of the projects I am starting to work with uses policies to protect the models. I am checking it view by view, model by model and I am fixing some issues like N+1 queries that it struggles with. One thing I am noticing though that baffles my mind is the huge amount of calls to policy checks I can see in the debug bar. For example, when I log in as admin, I can get to the list of users. For every user, the blade view uses @can('delete') directive to check if the user viewing the page is an admin and if he has a right to delete. In the debug bar I can see 26 calls to the gates and it takes 3.5 seconds to load the page ( I have already removed the unnecessary loading of other related models as they are not needed for the page at all). I do not thing checking the gates/policies 26 times is too much, but I have this on a page with only a few users. What would happen if I called such check on a page with 100 or more models? I find this call to @can within a @foreach loop to be a bit inefficient.
I am working of a premise here that if the auth()->user()->isAdmin() returns true, that it is true for all the loaded models (users in this case). User that is not an admin can not view this page. And if I take some user related models like projects for example, a regular user would only be able to view his own projects, so a check if the user can delete a project would be redundant.
So here is the question. Can I call the gate once at the top of the page and store the result in a a variable that I can then check within the loop?
Please or to participate in this conversation.