Skip to content

Adding sample data to the database

Clio Brichaut edited this page Jan 14, 2023 · 1 revision

For the first models:

  1. Fill in the definition in /app/database/factories/ProductFactory.php:
class ProductFactory extends Factory
{
	public function definition()
	{
		return [
			'name' => fake()->words(3, true),
			'price' => fake()->numberBetween(1, 10_000)
		];
	}
}
  1. Use that ProductFactory in /app/database/seeders/ProductSeeder.php to generate 10 sample products, after generating those provided in the assignment's /products.json:
class ProductSeeder extends Seeder
{
	public function run()
	{
		$assignmentInput = [
			['name' => 'Pioneer DJ Mixer', 'price' => 699],
			['name' => 'Roland Wave Sampler', 'price' => 485],
			['name' => 'Reloop Headphone', 'price' => 159],
			['name' => 'Rokit Monitor', 'price' => 189.9],
			['name' => 'Fisherprice Baby Mixer', 'price' => 120],
		];

		foreach ($assignmentInput as $product)
		{
			Product::factory()->create($product);
		}

		Product::factory(10)->create();
	}
}
  1. Call all seeders in /app/database/seeders/DatabaseSeeder.php to ensure they are properly loaded:
class DatabaseSeeder extends Seeder
{
	public function run()
	{
		$this->call([
			UserSeeder::class,
			BasketSeeder::class,
			ProductSeeder::class
		]);
	}
}
  1. Trigger DatabaseSeeder with ./vendor/bin/sail artisan db:seed. The database tables now contain the sample data.

Clone this wiki locally