Appearance
Factory
Use Eloquent Factories only for tests.
Keep factories in the
tests/Factoriesdirectory.Don't use the
HasFactorytrait in Model classes, use Factory classes directlyCall Factory classes directly in tests:
$user = UserFactory::new()->create([...]);Factory::definition()should set a valid default state (if possible) or not set any valid state.For states, implement separate methods:
phpfinal 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 } }