Laravel Seeders and Factories
A seeder fills a database with fixed starting rows. A factory builds a single test row with made-up values.
Make a seeder
This command creates a seeder file for tasks.
php artisan make:seeder TaskSeederFill the seeder
The run method inserts three fixed tasks. Seeders fill a database with fixed starting rows.
public function run(): void
{
Task::create(['title' => 'Buy milk', 'done' => false]);
Task::create(['title' => 'Write report', 'done' => true]);
Task::create(['title' => 'Call Ana', 'done' => false]);
}Run one seeder
This command runs only the TaskSeeder class.
php artisan db:seed --class=TaskSeederMake a factory
This command creates a factory file for the Task class.
php artisan make:factory TaskFactoryBuild one row
The factory fills in the missing values.
Task::factory()->create(['title' => 'Pack bag', 'done' => false]);Example
namespace Database\Seeders;
use App\Models\Task;
use Illuminate\Database\Seeder;
class TaskSeeder extends Seeder
{
public function run(): void
{
Task::create(['title' => 'Buy milk', 'done' => false]);
Task::create(['title' => 'Write report', 'done' => true]);
Task::create(['title' => 'Call Ana', 'done' => false]);
}
}
php artisan db:seed --class=TaskSeederKey points
- Seeder: a class that inserts fixed rows into a table.
- Factory: a class that builds one row with made-up values.
- Model: a class that stands for one table, such as the Task model for the tasks table.
- Use php artisan make:seeder TaskSeeder to create a seeder.
- Use php artisan db:seed to run the seeders.
- Use Task::create() to insert one row, or Task::factory()->create() to build one from a factory.
In this example, the seeder class defines a run method. The run method creates three tasks with fixed titles. The first task is unfinished, the second is finished, and the third is unfinished. The command runs only this seeder. The stored titles are Buy milk, Write report, and Call Ana.
Note
Seeders run after migrations, so the tables must exist first.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does a seeder do?