Adding extra fields in Laravel Spatie/laravel-permission Package
Written by Saran on
March 4, 2024Adding extra fields to the tables managed by Spatie/laravel-permission is a straightforward process. If you're wondering how to achieve this, you can simply follow the methods below. Let's delve into the steps required to extend the package's tables with additional fields.
Locate the Migration File
The migration file responsible for creating the tables used by the Spatie/laravel-permission package is typically named something like
**Date**_create_permission_tables.php. This file resides in the database/migrations/ directory of your Laravel project.
Modify the Migration File
Once you've located the migration file, open it for editing. Within this file, you'll find the schema definitions for creating the necessary tables. To add extra fields to roles table, such as "MyExtraField" add the line within migration's "up" method :
public function up(): void
{
//Add this line
Schema::table('roles', function (Blueprint $table) {
$table->string('MyExtraField')->nullable();
});
}
Once you've made the necessary changes to the migration file, save it and run the migration using Laravel's Artisan command-line tool:
If you find yourself in a situation where manual alterations to the permission table have caused issues, and running php artisan "migrate" command doesn't resolve the problem. In such cases, you might need to recreate the entire table structure. You can achieve this by executing the following Artisan command-line:
php artisan migrate:refresh
The php artisan migrate:refresh command in Laravel rolls back all of your migrations and then re-runs them. Essentially, it resets your entire database schema to its initial state defined by your migration files. So better be careful and backup your database before running the command.Remember, this method can be applied to other tables managed by Spatie/laravel-permission or any other Laravel package, hope it helps :)