Term of the week - Request lifecycle

Published on February 10th, 2020

Running a Laravel application has always seemed magical. I didn't quite understand how it all worked; I was just glad that it did. Until I decided to understand how Laravel's request lifecycle works.

It all boils down to the pretty standard HTTP request-response cycle. A user sends a request, the request is passed through various parts of the Laravel application and then is returned in the view as an HTTP response. Simple!

However, it is quite amazing what the request has to go through before the response is returned to the user:

The request lifecycle describes what happens as a request (whether via HTTP or via the console) comes into the Laravel application and generates a response, which is returned back to the user. Every user request enters your Laravel application via the public/index.php file. This file loads Composer's autoload.php, importing packages and any other PHP files necessary, without having to call include() or require() manually. The index.php file also bootstraps an instance of the Laravel framework and generates an instance of a Request object that represents the incoming user request. This incoming request object is sent through the Laravel's HTTP kernel or console kernel, depending on the type of the request. This kernel is the heart of a Laravel application; all of the application's middlewares are registered there. The kernel is responsible for taking the user request, bootstrapping the full application, loading configuration files and environment variables, handling exceptions, registering facades, and registering all of the application's service providers. Once it finishes its work, the kernel passes the request to the router for dispatching. The router dispatches the request to a particular route or controller and runs it through any required middleware, such as the auth middleware. Finally, after the route or controller generates a response, the response is is sent back to the user (via HTTP or the console output).

During my standard development process, the first time I think of the request is when it reaches the route and then the controller. I have never really thought about what needs to happen to even get to this stage. Following the code, digging deeper and deeper under the hood made me appreciate the work that had gone into developing Laravel.

Simply amazing!

I am glad that I have looked into how it all works, and I can understand the magic of Laravel just a little bit more. The following resources helped me:

Links

Ankita Tejani's Medium post

Josip Crnkovic's blog

Christoph Rumpel Laravel Core adventures video series

Matt Stauffer's Laravel book


← Go back