Skip to main content

Faster Seeds with Insert and Chunk

Premium
2:34

We've been focusing on optimizing Eloquent for data retrieval, but seeding large amounts of data efficiently is equally important.

This lesson examines strategies to significantly improve the performance of your Laravel database seeders.


The Challenge: Seeding Large Datasets

Consider a scenario where we need to seed:

  • Countries
  • Companies
  • Positions
  • Employees (20,000 records)

Each employee belongs to a country, a position, and a company.


Approach 1: Traditional For Loop with Eloquent Create

The conventional approach using Eloquent's create() in a loop:

public function run()
{
for ($i = 0; $i < 20000; $i++) {
Employee::create([
'name' => fake()->name(),
'company_id' => rand(1, 100),
'country_id' => rand(1, 100),
'position_id' => rand(1, 20)
]);
}
}

Other seeders are really quick but for employee it took 4,6 seconds for 20,000 employees.

This approach is slow because it executes 20,000 separate INSERT queries to the database.

The Full Lesson is Only for Premium Members

Want to access all of our courses? (30 h 50 min)

You also get:

55 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.