Let's start with the case where the model doesn't exist yet.
We need to run the following command:
php artisan make:model Product -mfs
We just created the following files:
- Product Model,
- Migration file (-m),
- ProductFactory (-f)
- ProductSeeder (-s)
In case the Product Model exists and we want to create only the ProductFactory, we need the following command:
php artisan make:factory ProductFactory --model=Product
We define the columns we want the products
table to have, in the migration file.
public function up(): void
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('description');
$table->timestamps();
});
}
We prepare the ProductFactory
with the fields we defined in the migration file. For more options about Factories
public function definition(): array
{
return [
'name' => fake()->word(),
'description' => fake()->paragraph(),
];
}
In the ProductSeeder
file, we can use the ProductFactory
like the example below: For more options about Seeders
public function run(): void
{
Product::factory(20)->create();
}
In case the Product Model exists and we want to create only the ProductSeeder, we need the following command:
php artisan make:factory ProductSeeder
All seeder files are declared in the database\seeders\DatabaseSeeder.php
file.
public function run(): void
{
$this->call([
UserSeeder::class,
ProductSeeder::class
// more seeders....
]);
}
Finally with the following command, we can fill the database with the fake data.
php artisan db:seed
Top comments (0)