← Back to all posts

Optimizing MySQL queries in real Laravel APIs

20 Nov 2025 · MySQL

Profiling slow endpoints and fixing them with proper indexing and query design.


Slow APIs are usually just slow database queries. Before thinking about caching, I first profile the queries and make sure they are as efficient as they can be.

Finding the slow query

In Laravel, I often start with the debug bar or simple query logging in local/dev environments. Once I know which query is slow, I run it with EXPLAIN in MySQL.

EXPLAIN SELECT * FROM orders
WHERE user_id = 123
ORDER BY created_at DESC
LIMIT 50;

If I see a full table scan or missing index, that’s usually my first fix.

Using the right indexes

For example, if I frequently filter by user_id and order by created_at, I’ll add a composite index:

ALTER TABLE orders
ADD INDEX idx_orders_user_created (user_id, created_at);

In Laravel migrations, I would express this with:

Schema::table('orders', function (Blueprint $table) {
    $table->index(['user_id', 'created_at'], 'idx_orders_user_created');
});

Many performance problems disappear with just the right indexing and avoiding N+1 queries.