Seeding
Manually populating database with test data while developing the application can be cumbersome. This is where database seeders help a lot. Seeders are classes that contain logic for populating the database with sufficient test data.
Lightpack provides a simple approach for populating test data with the help of database seeders.
Suppose you have a products table with following columns:
| products | id | title | description |
Creating Seeder
Fire this command from the root of your project:
php console create:seeder ProductsSeeder
This should have created a seeder class named ProductsSeeder in database/seeders directory.
The generated seeder class will look like this:
namespace Database\Seeders;
class ProductsSeeder
{
public function seed()
{
// ...
}
}
This class has a method named seed() where you can write the logic for populating products table with test data.
For example, here we populate 25 fake products as shown:
public function seed()
{
foreach(range(1, 25) as $index) {
$product = new Product;
$product->title = "Product {$index}";
$product->description = "Product description {$index}";
$product->save();
}
}
Here in each loop, we populate a new product using the Product model class.
Specifying Seeders
You can specify seeders inside the seed() method of DatabaseSeeder class. Seeders are run in the order of their specification.
public function seed()
{
$this->run([
BrandSeeder::class,
ProductSeeder::class,
]);
}
Note: The
run()method accepts either a single seeder class name (string) or an array of seeder class names. Each seeder'sseed()method is called in sequence.
Executing Seeders
As a final step, you need to execute all your seeders. For that, simply execute the following console command:
php console db:seed
You can skip confirmation prompt by passing --force flag.
php console db:seed --force
Note: If you want to seed a specific seeder, you can run it directly:
php console db:seed ProductsSeeder
Model Factory
In any robust application, realistic data is the foundation for meaningful development, testing, and demonstration. But handcrafting this data—or relying on repetitive, hardcoded examples—quickly becomes tedious and brittle as your project grows. This is where model factories come in: they empower you to generate rich, dynamic, and scalable datasets that mirror real-world scenarios with minimal effort.
Whether you’re populating a development environment, stress-testing features, or preparing impressive demos, model factories transform seeding from a chore into a powerful tool for quality and innovation.
Read the details about Lightpack's support for model factories in the Factory document.