The Spatie Laravel Permission package does indeed cache the permission checks for the duration of the request to avoid unnecessary database calls. Once a permission or role check is made, the result is stored in memory, and subsequent checks for the same permission or role within the same request will not hit the database again.
Here's how it works:
- When you check a permission or role for the first time in a request, the package retrieves the necessary data from the database.
- The retrieved data is then stored in the cache.
- Subsequent checks for the same permission or role will use the cached data instead of querying the database again.
This caching mechanism is built into the package and does not require any additional configuration. However, you can configure the cache duration and other cache-related settings in the config/permission.php configuration file if needed.
Here's an example of how you might check permissions using the Spatie Permission package:
use Spatie\Permission\Models\Permission;
// Checking a permission for the first time in a request
if (auth()->user()->hasPermissionTo('edit articles')) {
// This will retrieve and cache the permission check
}
// Checking the same permission again in the same request
if (auth()->user()->hasPermissionTo('edit articles')) {
// This will use the cached permission check and not hit the database
}
If you are experiencing performance issues with your current setup and are considering switching to the Spatie Permission package, it is worth noting that the package is well-maintained and widely used in the Laravel community. Additionally, since you mentioned that there is a first-party Filament plugin for the Spatie Permission package, it should integrate smoothly with your admin panel.
Before making the switch, you may want to review the documentation for the Spatie Permission package and the Filament plugin to ensure that it meets all your requirements and to understand how to properly implement it in your application.