---
title: "Eloquent Factories"
canonical_url: "https://handbook.propay.co.za/laravel/eloquent-factories"
---
# Eloquent Factories

## Tests

Eloquent Factory classes SHOULD be used only for tests. In the application context, Model methods, Actions and Services SHOULD be used instead.

To separate the "application" and "test" contexts even further, please:

- Keep all factories in the `database/Factories` directory (`Database\Factories` namespace).
- Use the `HasFactory` trait in Model classes.
- In tests, call Factory classes directly: `$user = UserFactory::new()->create([...]);`

**Factory::definition() should not set any state or set a default state only**

For Models that have a finite number of states ([Finite-state machine](https://en.wikipedia.org/wiki/Finite-state_machine), e.g. an `Article` can be in one of the `draft`, `published` or `archived` states), the `Factory::definition` method SHOULD NOT make a Model of any non-default state: the state should be set explicitly in the test.

For cases, when the state is not important, the recommendation is to create a method alias that underlines this (see ofAnyValidState):

<code-group>

```php [ArticleFactory.php]
final class ArticleFactory extends Factory
{
    /** @inheritDoc */
    public function definition(): array
    {
        return [
            'title' => fake()->sentence,
            'body' => fake()->paragraph,
        ];
    }

    public function draft(): self
    {
        return $this->state(['published_at' => null]);
    }

    public function published(): self
    {
        return $this->state([
            'published_at' => today(),
            'meta_description' => fake()->sentence,
        ]);
    }

    public function ofAnyValidState(): self
    {
        return $this->draft(); // or even return a random valid state
    }
}
```

</code-group>


## Sitemap

See the full [sitemap](https://handbook.propay.co.za/sitemap.md) for all pages.
