seeding - assign roles
Hi,
I am seeding my database and I am struggling to assign roles to my admins.
For example I have
//creates 2 clients
Client::factory()
->times(2)
//creates 3 institutions
->has(Institution::factory()->count(3)
//creates 3 "level 1" admins and attach in pivot table
->hasAttached(Admin::factory()->count(3))
//creates 3 users
->has(User::factory()->count(3))
)
->create();
I need to give a role to the admins. I understand the admin needs be persisted for the role to be applied.
$admin->assignRole('Admin level 1');
I can not really use
/**
* Configure the model factory.
*
* @return $this
*/
public function configure()
{
return $this->afterMaking(function (Admin $admin) {
//
})->afterCreating(function (Admin $admin) {
$admin->assignRole('Admin level 1');
});
}
as I need to create other types of users in other factories.
Any suggestions?
Hi @rffred
I have yet to upgrade to Laravel 8 yet, so not 100% if this will work or not.
But you could try adding a state method
so you would call Client::factory()->times(2)->isAdmin()->create()
And that would apply your afterCreating logic
/**
* Configure the model factory.
*
* @return $this
*/
public function isAdmin()
{
return $this->afterMaking(function (Admin $admin) {
//
})->afterCreating(function (Admin $admin) {
$admin->assignRole('Admin level 1');
});
}
I would assume that something like this is available, as it is something that you could do with states on the legacy style factories.
Please or to participate in this conversation.