Video Version of the Lesson
[Only for premium members]
[Only for premium members]
[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.
Consider a scenario where we need to seed:
Each employee belongs to a country, a position, and a company.
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.