Skip to content

Factory

  1. Use Eloquent Factories only for tests.

  2. Keep factories in the tests/Factories directory.

  3. Don't use the HasFactory trait in Model classes, use Factory classes directly

  4. Call Factory classes directly in tests: $user = UserFactory::new()->create([...]);

  5. Factory::definition() should set a valid default state (if possible) or not set any valid state.

  6. For states, implement separate methods:

    php
    final class ArticleFactory extends Factory
    {
        /** @inheritDoc */
        public function definition(): array
        {
            return [
                'title' => $this->faker->sentence,
                'body' => $this->faker->paragraph,
            ];
        }
    
        public function draft(): self
        {
            return $this->state(['published_at' => null]);
        }
    
        public function published(): self
        {
            return $this->state([
                'published_at' => today(),
                'meta_description' => $this->faker->sentence,
            ]);
        }
    
        public function ofAnyValidState(): self
        {
            return $this->draft(); // or return a (random) valid state
        }
    }