i have 2 tables user and roles, i want to create a user factory so that i add an admin role for that user created. I have the user table with (id,name,...,age ) and the roles table with (id, user_id and role_name). i want to make a factory that creates a user and gives him the role of an admin. (remember the role is accessed through the hasmany relationship from the user model ) how can i achieve this.
public function definition(): array
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
];
}
/**
* Indicate that the model's email address should be unverified.
*/
public function unverified(): static
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
public function configure()
{
return $this->afterCreating(function (User $user) {
// Create and assign a role to the user
$role = Role::factory()->create();
$user->roles()->attach($role);
});
}