Seeders and factories
| A seeder class | |
| Factory states | |
| Run them | |
| Seed dev data |
A seeder class
A seeder is a plain class with a run method that writes rows into the database. Seeders live in database/seeders and usually call create on one model at a time.
Keep each seeder focused on one table so sample data stays easy to read and easy to rerun from scratch.
use App\Models\User; use Illuminate\Database\Seeder; class UserSeeder extends Seeder { public function run(): void { User::create([ "name" => "Demo User", "email" => "demo@example.com", ]); } }
Factory states
Factories generate fake models in bulk when one hand written row is not enough. The default factory knows valid values for every column, and a state tweaks one detail such as an unverified address.
Combine a count with a state to build exactly the data set a feature needs for a manual test.
use App\Models\User; User::factory()->create([ "name" => "Demo User", ]); User::factory()->count(10)->create(); User::factory()->unverified()->create();
Run them
Generate a new seeder file with the canonical maker command, then run all seeders with the seed command. The first command prints the path of the created file.
php artisan make:seeder UserSeeder
INFO Seeder created successfully.
Run the whole set any time the local database needs a fresh start:
php artisan db:seed
INFO Seeding database.
Seed dev data
The main DatabaseSeeder calls the smaller seeders in order, so one command seeds everything. List only development helpers there and keep production data out of the file.
Real projects often guard extra demo content behind a local environment check so staging and production stay clean.
use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { public function run(): void { $this->call([ UserSeeder::class, ]); } }
Next: Validation
Article author: Arthur Isaev