DEV Community

Cover image for How to seed Roles in Laravel using Seeder. (Tips)
T9
T9

Posted on

How to seed Roles in Laravel using Seeder. (Tips)

I was looking for a way to seed roles to the database after refresh, I couldn't find a suitable solution on the internet and I tried to use Faker function called randomElements();, but It migrated the roles in a random order.

Code in Factory RoleFactory.php

protected $role = Role::class;
    public function definition()
    {
        return [
            'Role' => $this->faker->unique()->randomElement($array = array('Admin', 'Student', 'Supervisor')),
        ];
    }
Enter fullscreen mode Exit fullscreen mode

However, I found a way that worked for me on the Laravel Docs using Array seeding.
First run the command below:

php artisan make:seeder RoleSeeder
Then write/copy the following code to RoleSeeder.php

class RoleSeeder extends Seeder
{
public function run()
    {
        Role::factory(3)->state(new Sequence(
            ['id' => 1, 'Role' => 'Admin'],
            ['id' => 2, 'Role' => 'Student'],
            ['id' => 3, 'Role' => 'Supervisor'],
        ))->create();
    }
}
Enter fullscreen mode Exit fullscreen mode

Lastly, run the following command.
php artisan db:seed --class=RoleSeeder

I hope it is useful.

Top comments (0)