Preventing N+1 Queries & Optimizing Composite Indexes in Laravel
1. Catching N+1 Queries Automatically in Local Development
The fastest way to eliminate accidental lazy loading across Blade views, Livewire components, and API resources is to enable Model::preventLazyLoading() inside AppServiceProvider::boot() whenever the application is not running in production:
use Illuminate\Database\Eloquent\Model;
public function boot(): void
{
Model::preventLazyLoading(! $this->app->isProduction());
}
Whenever a loop accesses an unloaded relationship, Laravel throws a LazyLoadingViolationException immediately during development instead of silently firing 500 separate SELECT statements.
2. Designing Composite Indexes Using the Equality-First Rule
Adding single-column indexes on every WHERE column rarely gives MySQL the best execution plan. InnoDB typically chooses a single index per table reference; if your dashboard query filters by account_id, status, and a date range on created_at, column order inside a composite index determines whether MySQL performs an index range scan or a slow filesort.
// Query pattern:
// WHERE account_id = ? AND status = ? AND created_at >= ? ORDER BY created_at DESC
Schema::table('call_logs', function (Blueprint $table) {
// Equality columns first (account_id, status), range/sort column last (created_at)
$table->index(['account_id', 'status', 'created_at'], 'idx_calls_account_status_created');
});
Because B-Tree composite indexes are sorted strictly left-to-right, placing equality predicates (=) before range predicates (>=, BETWEEN) allows MySQL to narrow down to the exact tenant and status slice and read rows already sorted by created_at without sorting on disk.
3. Constrain Eager-Loaded Columns to Reduce Memory Overhead
When eager loading parent or child records across large result sets, select only the foreign key and display columns rather than hydrating full TEXT or JSON payload columns:
$calls = CallLog::query()
->select(['id', 'account_id', 'campaign_id', 'caller_number', 'duration', 'created_at'])
->with(['campaign:id,name'])
->where('account_id', $accountId)
->where('status', 'completed')
->latest('created_at')
->paginate(50);
Written by Gulfaraz Arshad
Software Developer at Cruise Brains specializing in Laravel, PHP, MySQL performance optimization, and high-throughput API architectures.