F
Filament2mo ago
Akimbo

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:
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
Jump to solution
7 Replies
Akimbo
AkimboOP2mo ago
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 cache
Solution
Mohamed Ayaou
Mohamed Ayaou2mo ago
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
Mohamed Ayaou
Mohamed Ayaou2mo ago
public static function table(Table $table): Table
{
$condition = ...;
return $table
->...
}
public static function table(Table $table): Table
{
$condition = ...;
return $table
->...
}
toeknee
toeknee2mo ago
You could just write it into the cache. But did you place this as a closure? This should reduce the amount of calls too.
Akimbo
AkimboOP2mo ago
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.
toeknee
toeknee2mo ago
So chuck a function in the resource
public static function getCachedIsVisiblecheck()
{
return Cache::remember('cached_is_visible_check', now()->addMinutes(10), function () {
return auth()->user()->can('view Permissions'); // Runs the query only if not cached
});
}
public static function getCachedIsVisiblecheck()
{
return Cache::remember('cached_is_visible_check', now()->addMinutes(10), function () {
return auth()->user()->can('view Permissions'); // Runs the query only if not cached
});
}
Then call: self::getCachedIsVisiblecheck()
Akimbo
AkimboOP2mo ago
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.

Did you find this page helpful?