In resources, where do I put database queries that I only want to run once?
The
->hidden()
method runs 5 times per row in my app, and that seems to be the default with filament. I really need the result of it to be based on a user permission, but that would mean fetching that permission lots of times when I don't need it.
Is there a place in a resource similar to mount
where I can load something once and access it?Solution:Jump to solution
Not a great idea but you may just load it insude the table method as a variable as long as it isn't needed for the resource class itself
7 Replies
And the reason this is also an issue for me is I can't get spatie laravel-permissions to actually use the cache. It uses it when getting all permissions but the
can
and hasPermissionTo
queries don't seem to leverage the cacheSolution
Not a great idea but you may just load it insude the table method as a variable as long as it isn't needed for the resource class itself
You could just write it into the cache. But did you place this as a closure? This should reduce the amount of calls too.
I did it as an anonymous function. As far as I'm aware, that does not make it called only once but everytime
isHidden
is run in Filament.So chuck a function in the resource
Then call: self::getCachedIsVisiblecheck()
That's a fine answer, but it brings a completely different set of problems that using a Cache brings. Caching should not be the go to for a problem with the frameworks lifecycle.
Like you say, I'd expect a supplied closure to run once per row, but that's not the case with
->hidden()
. Running it 5 times per row seems unnecessary. It doesn't get new parameters between each call.
I will mark Mohamed's answer for now because I don't see downsides to it, but it'd be nice to see Filament have more control over stuff like this in the future.