Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

spycrabo's avatar

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?

0 likes
2 replies
tykus's avatar

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();
		});
	}

spycrabo's avatar

In my actual code I have return statement but it does not change the behaviour

Please or to participate in this conversation.