I have a Laravel with a role/permission system built with Spatie's package. Once I deploy the initial version, I may develop new features and these features may be associated with new roles/permissions.
My question what is the best way to add these new roles/permissions to production database. I may use seeder but I read somewhere that DB seeding is good for development only.
How do you guys handle such situations? What is your approach?
There are multiple ways. If it's something that should be added to your tests (like tests that rely on the new role) I would seed it. You can even seed in a migration to have it run with the rest of your migrations, and it would then be part of your tests as well. Only problem with this, is that you can never prune migrations.
If it's not something you need in your tests, you can either make a page to manage the roles and permissions, or you can simply add them using the built in artisan commands
I have done this in the past with migrations. Create a migration and instead of the usual database stuff, inside write the code you need that creates the additional permissions or roles.
Doing it a migration ensures that it only gets run the once.
@Snapey Doing this in migrations in convenient and works.
Just be aware that if you ever squash your migrations using artisan schema:dump - the resulting SQL file will only include the schema, and not any data updates made from a migration. This makes data insertions inside migrations a bit dangerous. On top of that, som code changes risks breaking the migration if you run artisan migrate:fresh. I have for example noticed that adding soft deletes to an existing model has broken old migrations.
So, in short, I'd recommend avoiding doing any data changes in migrations. If one needs to make large inserts or updates, I would instead make sure that the code is compatible both with and without the update, and then run the changes as a one-time artisan command post deployment.
Since then I wrote a sync permissions artisan command. The command holds an array of required permissions. When running the command, it ensures that all permissions exist. Any no longer in the array are removed.
When adding new permissions, I add them to the array and then run the sync permissions command.
However, since then, I have written a package that uses an enum file for permissions and stopped using the spatie package totally.
On this matter, creating a new migration to add database records after deployment definitely work. We did that before. But if that approach is abused, PHPUnit tests cases and CI/CD will be slow down drastically.