Certainly! Here’s a well-rounded answer to the question:
Solution:
Extending the Spatie Permission models in your Laravel application is generally considered best practice if you anticipate the need for customization or future extension. Even if you don’t currently require any custom behavior, having your own model classes allows greater flexibility and maintainability down the line.
Why Extend?
- Custom Attributes: Add new fields/columns or relationships specific to your app.
- Custom Methods: Introduce helper methods or business logic relevant to your app’s requirements.
- Organization: Placing models in your
app/Modelsdirectory keeps code organized and consistently structured.
How to Extend
Spatie’s documentation itself recommends extending their models if you need customization. Here’s how:
1. Create Your Role and Permission Models:
namespace App\Models;
use Spatie\Permission\Models\Role as SpatieRole;
class Role extends SpatieRole
{
// Add your custom methods or relationships
}
namespace App\Models;
use Spatie\Permission\Models\Permission as SpatiePermission;
class Permission extends SpatiePermission
{
// Add your custom methods or relationships
}
2. Update the config/permission.php:
Change these lines to use your custom classes:
'models' => [
'permission' => App\Models\Permission::class,
'role' => App\Models\Role::class,
],
Conclusion
- If you don’t foresee any customization, you can use the default models.
- However, it’s safe and maintainable to immediately extend them as your own, even if you leave them empty initially.
- This future-proofs your codebase and adheres to good organizational practices.
Reference:
Spatie Laravel Permission Docs - Using your own models
In summary:
Yes, it is good practice to extend Spatie Permission models in your Laravel application for better maintainability and easier customization.