Laravel interview question · Most asked
Walk me through the lifecycle of an HTTP request in Laravel.
Summary
The request enters public/index.php, the application is bootstrapped, the HTTP kernel runs it through global middleware, the router matches a route and runs route middleware, the controller returns a response, and the response travels back out through the middleware before being sent.
Longer Answer
public/index.php loads Composer's autoloader and creates the application from bootstrap/app.php. The HTTP kernel bootstraps the framework: it loads configuration and environment, registers error handling, and registers and then boots every service provider, which is where most of the framework (database, queue, routing, validation) is wired into the container.
The request is then sent through the global middleware stack (trimming strings, maintenance mode, trusted proxies). The router matches a route, applies its middleware groups (web adds sessions, cookies and CSRF; api is stateless), resolves route-model bindings, and calls the controller or closure with its dependencies injected from the container.
Whatever the controller returns (a view, an array, a model, a Response) is converted into a Response object and passes back out through the same middleware in reverse order, which is how middleware can modify responses. Finally the response is sent and terminable middleware runs.
Key Points
- Entry point
public/index.php, app built inbootstrap/app.php. - Service providers register, then boot.
- Global middleware, route matching, route middleware, controller.
- The response goes back out through middleware in reverse order.
Deep dive: Request Lifecycle course: The Laravel Request Lifecycle
Explanation
What interviewers look for
A clear sequence with service providers and middleware in the right places. Senior candidates mention that knowing the lifecycle tells you where to hook in (provider, middleware, controller) and what runs on every request.
Follow-up questions
- Where would you add code that must run on every request?
- What changes in this lifecycle when the app runs under Octane?
More most-asked Laravel questions
- How do database transactions work in Laravel, and what pitfalls should you know?
- Gates or policies: how does authorization work in Laravel?
- What is the service container, and how does dependency injection work in Laravel?
- Which Artisan commands would you run when deploying Laravel to production, and why?
- How do you validate requests in Laravel? Why use Form Requests?
- What is the N+1 query problem in Eloquent and how do you prevent it?
- What is mass assignment, and how do $fillable and $guarded protect against it?
- How do queues work in Laravel?