Raftx24
Raftx24

Reputation: 316

High memory usage eloquent laravel in big queries

When I query with more than 1000 records, eloquent takes a lot of memory.
How can I solve it?!
For example, Imagine there is a users table with 10000+ records, and I want to run the below statement.

User::whereIsActive(1)->get()
    ->each(fn (User $user) => $user->notify())

Upvotes: 1

Views: 3299

Answers (1)

stefanzweifel
stefanzweifel

Reputation: 1454

You can use each() directly in the Eloquent-Builder chain. By using each() Laravel automatically chunks the result by 1000.

User::whereIsActive(1)->each(fn (User $user) => $user->notify());

If you want lower chunks, add a 2nd argument to each()

User::whereIsActive(1)->each(fn (User $user) => $user->notify(), 100);

Your original code executes get() before each(). get() executes the database query and loads all results into memory and then uses Laravel collections' each() to chunk through them. Thats why it's using so much memory.

Upvotes: 3

Related Questions