Introduction
Laravel provides first-class support for testing database-driven applications. You can combine database reset traits, model factories, and test-specific assertions to write fast and reliable feature tests. In most cases, start withRefreshDatabase. It keeps tests isolated while remaining faster than fully rebuilding the database every time.
Resetting the database after each test
To prevent data from one test affecting another test, use one of Laravel’s database reset traits.RefreshDatabase checks whether the database schema is already up to date. If it is, Laravel runs each test in a transaction. If it is not, Laravel runs migrations first.
If you need a full reset strategy instead of transaction-based isolation, use the following traits:
| Trait | Behavior | When to use |
|---|---|---|
RefreshDatabase | Uses transactions if schema is current; migrates when needed | Default choice for most test suites |
DatabaseMigrations | Runs migrations for each test | When you need migration-level lifecycle behavior in every test |
DatabaseTruncation | Truncates tables between tests | When transactions are not suitable and truncation fits your DB workflow |
Model factories
Before asserting behavior, you often need test data. Laravel model factories provide expressive defaults for creating Eloquent models. For full factory definitions and advanced states / relationships, see Eloquent Factories.Running seeders
Use theseed() method to populate data during tests. Without arguments, it runs DatabaseSeeder. You can also run a specific seeder class or an array of classes.
RefreshDatabase by using attributes:
#[Seeder(...)]: