I Fixed My Slow Laravel App With 4 Eloquent Changes — Here's What Actually Helped
My Laravel app worked fine for months. Then the users table passed 50,000 rows, the posts page started taking four seconds to load, and a nightly export job started dying with "Allowed memory size exhausted" at 3 a.m. I did not rewrite the app. I did not add Redis. I changed four Eloquent habits, and the same pages got fast again. Here is what actually helped, in the order that mattered most. 1.…
The author's Laravel application had been running smoothly for months until the users table grew to 50,000 rows. This caused the posts page to take four seconds to load and a nightly export job to fail due to memory exhaustion. The author did not rewrite the app or add Redis, but rather made four changes to how they used Eloquent.
These changes significantly improved the app's performance. The first change was eager loading, which replaced multiple queries with just two. The second change was replacing count() with exists() to check for the existence of an email, reducing the workload on the database. The third change was chunking the data to avoid exhausting memory when processing large amounts of records.
The final change was letting the database handle simple calculations instead of fetching rows to compute them in PHP. The author emphasizes the importance of identifying and fixing these common Eloquent issues, using Laravel Telescope to measure the performance improvements. They invite readers to share their own experiences fixing slow Eloquent queries.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to