Laravel interview question · Most asked
A Laravel endpoint is slow. How do you find and fix the cause?
Summary
Measure first: look at query count and time (Telescope, Debugbar, slow query log, APM), then fix the biggest cost, usually N+1 queries, missing indexes, too much data loaded, or slow external calls in the request.
Longer Answer
Typical findings, roughly in order of frequency:
- N+1 queries: eager load; enable
preventLazyLoadingin development. - Missing indexes: run
EXPLAINon the slow queries; add composite indexes matchingWHEREandORDER BY. - Loading too much:
get()on large tables,SELECT *, hydrating thousands of models; paginate and select columns. - Synchronous side effects: email, PDF generation, third-party APIs; queue them.
- Repeated expensive computation: cache with a TTL.
- Framework overhead:
php artisan optimize, OPcache, Composer optimized autoloader; Octane if bootstrap cost dominates.
Verify each fix with the same measurement, and add a regression guard (query-count assertions in tests, APM alerts).
Key Points
- Measure before changing anything.
- N+1, indexes, data volume, synchronous I/O.
- Cache and queue where appropriate.
- Confirm with the same metric.
Explanation
What interviewers look for
A systematic, measurement-driven approach. Jumping straight to 'add Redis' or 'use Octane' is a red flag.
Follow-up questions
- How would you assert the number of queries in a test?
More most-asked Laravel questions
- How do you validate requests in Laravel? Why use Form Requests?
- Gates or policies: how does authorization work in Laravel?
- What is mass assignment, and how do $fillable and $guarded protect against it?
- How do database transactions work in Laravel, and what pitfalls should you know?
- Which Artisan commands would you run when deploying Laravel to production, and why?
- What is the service container, and how does dependency injection work in Laravel?
- What is the N+1 query problem in Eloquent and how do you prevent it?
- How do queues work in Laravel?