You Need Data for Development and Testing

Your Laravel project has a database, you just started development and you want to fill it with data.

Write a Database Seeder

The textbook approach is to write a factory to generate instances of the class using Faker for faking values. Like,


And then a seeder, one for each class, that uses the factory. Such as:


Handling Relationships

While seeding one class, you need to generate a reference to an instance in another class that is also being generated. The best approach that we found is to randomly generate a reference based on knowing how many instances of the referenced class are going to be generated.

If the Order class references the Product class, and we know the seeder of the later is going to generate 300 instances, then we generate the reference field of the Order as a number between 1 and 300. Such as:

in OrderFactory.php.

Seeding Media

We have a Product model where each product has an image. We use the Laravel Media Library to manage our images.

We seed the Product model with media from a given fixed set of images. The folder original contains our initial set of images. The seeder for the model Product will randomly pick an image from that folder and assign it to the product.


Written by

Open source, Mobile, Web, Cloud, Server - Independent Information Technology and Services Professional

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store