What is the HasFactory trait and how does it work?
Answer
The HasFactory trait (added to Eloquent models) provides a static factory() method for creating model factory instances. When you call User::factory(), Laravel resolves the corresponding factory class (Database\Factories\UserFactory) by convention. The trait provides: User::factory()->make() (new instance without saving), create() (save to DB), count(5)->create() (create 5 instances), state(["role" => "admin"]) (override specific attributes), create(["name" => "Alice"]) (override on creation). Factories support relationships: User::factory()->has(Post::factory()->count(3))->create() creates a user with 3 posts, handling all foreign keys automatically. Factory sequences allow cycling through values: factory()->sequence(["active" => true], ["active" => false]).
Previous
What is Laravel's testing with Mocking and Faking?
Next
What is firstOrCreate and firstOrNew in Eloquent?