I would want to write something like this:
class UserFactory extends Factory
{
public function withRoles(array $roles) {
$factory->state(function (array $attributes) use ($roles) {
$user = User::find($attributes['id']);
$roles = Role::whereIn('title', $roles)->get();
$user->roles()->attach($roles);
return $user;
});
}
Unfortunately, id
is not available in this $attributes
nor, I guess, in the state methods of a factory.
What could I do to solve this problem?
CodePudding user response:
You can use a callback function in the configure function of the UserFactory:
class UserFactory extends Factory
{
/**
* Configure the model factory.
*
* @return $this
*/
public function configure()
{
return $this->afterMaking(function (User $user) {
})->afterCreating(function (User $user) {
//
});
}
// ...
}
This would do it every time you use the create / make UserFactory functions.
Alternatively you may use the built in ->hasAttached() or ->has() method e.g.
$user = User::factory()
->count(3)
->has($roles)
->create();
This is all outlined pretty well in the Laravel documentation for factories: https://laravel.com/docs/9.x/eloquent-factories#factory-states