DEV Community

JohnDivam
JohnDivam

Posted on

Laravel app was slow. Here's how I fixed it

Imagine fetching 100 users, each with related posts and comments.
Without optimization, your app might execute 1000+ queries just to load a single page!
The result? Slow performance, wasted resources, and frustrated users.
Let’s fix it step by step :

1️⃣** Eager Loading ->with()**
Instead of making one query per related record, load relationships in advance.

Before:

$users = User::all();
Enter fullscreen mode Exit fullscreen mode

After:

$users = User::with('posts', 'comments')->get(); //Faster. Cleaner. Efficient.
Enter fullscreen mode Exit fullscreen mode

2️⃣ Database Indexing
Add indexes to columns you frequently query or use in WHERE, JOIN, and ORDER BY clauses.

Example:

CREATE INDEX idx_user_email ON users(email); //Query time improved from 800ms → 50ms
Enter fullscreen mode Exit fullscreen mode

3️⃣ Query Caching (Laravel Cache)
Cache repeated queries or expensive operations using Laravel’s built-in caching.

Example:

$users = Cache::remember('users_with_posts', 60, function() {
    return User::with('posts')->get();
});
Enter fullscreen mode Exit fullscreen mode

4️⃣ Lazy Loading Assets (Images, Videos, etc.)
Optimize your frontend performance by loading assets only when they’re visible.

<img src="image.jpg" loading="lazy" alt="User profile"> 
Enter fullscreen mode Exit fullscreen mode

Faster page rendering and lower initial load times.

5️⃣ Optimize Select Queries (Avoid SELECT *)
Fetching unnecessary columns bloats your response and slows queries.

Before:

$users = User::with('posts')->get();
Enter fullscreen mode Exit fullscreen mode

After:

$users = User::select('id', 'name', 'email')
             ->with('posts:id,user_id,title')
             ->get(); //Only the data you need — smaller payloads, faster delivery.
Enter fullscreen mode Exit fullscreen mode

Final Thoughts
Performance optimization isn’t a one-time task — it’s an ongoing discipline.
By combining eager loading, indexing, caching, and smart query design, you can turn a slow, bloated app into a lightning-fast experience ⚡.

Top comments (0)