Optimize Laravel’s Database Seeders

Piyuri Sahu
2 min readDec 1, 2017
Optimising Seeder in Laravel

I have been working in a Laravel project which requires me to generate a good amount of users’ dummy data to our databases automatically. In other words, database seeding.

Below is a basic UserTableSeeder class that we were using to create dummy data of users.

In above seeder, we create dummy data using User::create().

This runs an SQL query like INSERT into users VALUES (‘username’,’role’,’email’….) each time a user is created.

SQL allows us to do mass insertions (INSERT INTO table_name ( Column1, Column2 ) VALUES ( Value1, Value2 ), ( Value1, Value2 )) and it can cut down significant time of the original seeding… which is awesome..

So now I write the code below, which will run just 1 query instead of 10.

This works like a charm. It gets the queries down to a single one.

But then I have other seeders, where I have to add all attributes and they are more complex and frustrating.

So now I can think of using some factory method where I can take most of the attributes. So I can do something like this:

So now I provide only necessary data; rest of the data will be given by ModelFactory.

As your code grows more complex, you may need to optimize a few things for increased performance, and these optimizations in seeder should help you along the way.

--

--

Piyuri Sahu

Application-developer at Technogise Software Solution