AmoyCreative

Read Time: 3 minutes |

Easily Seed Permissions in Laravel + Spatie

Seeding a database is essential in any Laravel project, especially when setting up initial data. In this blog post, we will create a seeder to populate permissions in your database. This is particularly useful in applications that require role-based access control.

Step 1: Setting Up Your Seeder Class

First, you need to create a seeder class. In this example, we will name it  PermissionSeeder. Open your terminal and run the following Artisan command:

This command will create a new file in the database/seeders directory.

Step 2: Define the Seeder Logic

Open the newly created PermissionSeeder.php file and define the permissions you want to seed. Here is an example of how you can do it:

In this code snippet:

  1. We define a list of policies such as ‘employees’, ‘users’, etc.
  2. For each policy, we create multiple permissions (view, create, update, delete, restore).
  3. Each permission is inserted into the  permissions table with a name, guard name, and timestamps.

Step 3: Run the Seeder

To run your seeder, you need to call it from the DatabaseSeeder class. Open the DatabaseSeeder.php file located in the database/seeders directory add the following line to the run method:

Now, you can run the seeder using the Artisan command:

This will execute the run method of the PermissionSeeder class and populate the  permissions table with the defined permissions.

Conclusion

Seeding your database with initial permissions is a straightforward process in Laravel. By following the steps outlined in this post, you can easily set up different permissions for different policies in your application. This approach ensures that your database is populated with consistent and accurate data, making it easier to manage roles and permissions across your application.

Happy coding! If you have any questions or run into any issues, feel free to leave a comment below.