Passing data to factory callback When writing model factories in Laravel 8 how can I pass some data to factory callback afterCreating?
For example, I have model Entity and it has roles. I want to define some flags to attach roles after creating. I tries this one:
class EntityFactory extends Factory
{
protected bool $roleFoo = false;
protected bool $roleBar = false;
public function configure()
{
$this->afterCreating(function ($entity) {
// always false
if ($this->roleFoo)
$entity->attachRoleFoo();
// always false too
if ($this->roleBar)
$entity->attachRoleBar();
});
}
public function roleFoo()
{
$this->roleFoo = true;
return $this;
}
public function roleBar()
{
$this->roleBar = true;
return $this;
}
}
But the factory instance's attrubites are always false inside afterCreating callback. How I can achieve needed functionality?
You must return from the configure method:
public function configure()
{
return $this->afterCreating(function ($entity) {
// always false
if ($this->roleFoo)
$entity->attachRoleFoo();
// always false too
if ($this->roleBar)
$entity->attachRoleBar();
});
}
In my actual code I have return statement but it does not change the behaviour
Please sign in or create an account to participate in this conversation.