Courses

Laravel 12 Eloquent: Expert Level

Faster Seeds with Insert and Chunk

You're reading a FREE PREVIEW of a PREMIUM course.
Summary of this lesson:
- Factory with create() runs separate queries for each record
- insert() with chunking reduces queries and is faster
- Chunked approach doesn't trigger timestamps or model events

Video Version of the Lesson

[Only for premium members]

Link to the repository

[Only for premium members]

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 38 video+text lessons of this course? (1 h 34 min)

You also get:

  • 77 courses
  • Premium tutorials
  • Access to repositories
  • Private Discord