Skip to main content
RU Digital Services
MySQL & Performance 3 min read •

Fixing N+1 Queries and Designing Composite Indexes in MySQL 8 for Laravel Apps

A Laravel dashboard that feels fast with 20 test rows will grind to a halt at 50,000 rows unless you understand eager loading and leftmost composite index ordering.

AA
Aaqib Khalique
Chief Technology Officer (CTO) • RU Digital Services

When a Laravel application slows down in production, the database is almost always the first place to look—and usually the easiest win. You rarely need a bigger server; you need fewer queries and better indexes.

Catching N+1 Queries Automatically During Development

An N+1 query happens when you load 50 enrollments in 1 query and then access $enrollment->student->user->full_name inside a Blade loop, triggering 100 extra queries. Add one line in AppServiceProvider::boot() so Laravel throws an exception locally the moment any developer introduces lazy loading:

use Illuminate\Database\Eloquent\Model;

public function boot(): void
{
    Model::preventLazyLoading(! app()->isProduction());
}

Now every query that needs nested relations must declare them upfront:

$enrollments = Enrollment::with(['student.user', 'cohort', 'payments'])
    ->latest('id')
    ->paginate(25);

Leftmost Prefix Rule for MySQL 8 Composite Indexes

Suppose your admin inbox runs this query thousands of times a day:

SELECT * FROM contact_inquiries
WHERE status = 'new'
ORDER BY created_at DESC
LIMIT 20;

Putting separate single-column indexes on status and created_at forces MySQL to pick one index and perform a slow filesort on the remaining rows. Instead, create a single composite index in the exact order of equality column first, range/sort column second:

$table->index(['status', 'created_at']);

Run EXPLAIN on the query in MySQL 8. You want to see type: ref, your composite index under key, and no Using filesort in the Extra column.

Never Run Queries Inside Blade Templates

Another silent performance killer is dropping \App\Models\Faq::count() or TeamMember::active()->get() directly inside Blade views or shared layouts. Move read-only marketing queries into your controller and wrap them in Cache::remember(), flushing those keys inside the model's booted() saved and deleted events so updates appear immediately without hitting MySQL on every visitor click.

Written by Aaqib Khalique

Need help architecting a Laravel backend, Kotlin Android app, or joining our weekend engineering cohort?

Related Engineering Guides

All articles →
Send Inquiry WhatsApp Chat
Cookie & Privacy Notice

We use essential cookies to maintain security and authentication, as well as optional analytical cookies to deliver relevant content and analyze traffic. Read our Privacy Policy.