Step 1: Setting Up Your Seeder Class
PermissionSeeder
. Open your terminal and run the following Artisan command:
php artisan make:seeder PermissionSeeder
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:
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class PermissionSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
$policies = ['employees', 'logs', 'permissions', 'roles', 'users', 'profile'];
foreach ($policies as $policy) {
$actions = ['view', 'create', 'update', 'delete', 'restore'];
foreach ($actions as $action) {
DB::table('permissions')->insert([
'name' => $policy . '-' . $action,
'guard_name' => 'web',
'created_at' => now(),
'updated_at' => now(), // Including updated_at field to avoid potential issues
]);
}
}
}
}
In this code snippet:
- We define a list of policies such as ‘employees’, ‘users’, etc.
- For each policy, we create multiple permissions (view, create, update, delete, restore).
- 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 theDatabaseSeeder.php
file located in the database/seeders
directory and add the following line to the run
method:
public function run(): void
{
$this->call(PermissionSeeder::class);
}
php artisan db:seed
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.