Request Lifecycle
Introduction
You feel more confident with a tool when you understand how it works. This guide gives you a high-level tour of a Laravel application: how it starts, what happens to a request on its way to your handler, and how the response gets back to the browser. Along the way, you'll see where to build services, add middleware, and handle errors. If some of the terms are new, don't worry. Each one links to the guide that covers it, and a rough picture of the whole is enough to start.
Starting up
Creating the application
You describe your application in bootstrap/app.go, where the Options function returns a laravel.Options value. The options list your routes, middleware, migrations, commands, and other settings, but nothing runs yet. The main function in main.go passes them to laravel.Run:
1func main() {2 laravel.Run(bootstrap.Options())3}1func main() {2 laravel.Run(bootstrap.Options())3}
Your tests build the same application from the same options, through the tests.New function in tests/tests.go.
Whether your application is serving requests or running a test, Laravel puts it together in this order:
- Configuration. Laravel finds your application's root directory, reads your configuration from the environment and your
.envfile, and runs yourConfigurefunction, if you have one, for settings an environment variable can't hold well, such as a second database. - Packages register. Each of your packages sees your final configuration and adds its routes, middleware, views, migrations, and commands.
- Your application registers. If you provide a
Registerfunction inbootstrap/app.go, Laravel calls it after your packages so you can add custom stores, mailers, queue connections, or OAuth providers usingapp.Env(). Laravel then builds its default middleware, lets your packages change the lists, and passes them to yourMiddlewarefunction, so your changes come last. Your route files inroutes/run after your packages' routes. Laravel also prepares the database, cache, sessions, and queue that your configuration describes, though it doesn't connect to the database until the first query. - Laravel checks the result. A mistake such as an invalid environment variable or two routes that answer the same request stops the application. Laravel lists every problem at once, and
laravel.Runprints them and exits before your application accepts a single request.
Finally, Laravel calls services.New, which builds your application's own services, such as the clients for the APIs it calls. It builds them once, and every request, job, and command shares them from then on.
Laravel keeps none of the application's state in global variables. Instead, it puts the application in the context of each request, job, and command it runs. That's why each of your tests may build an application of its own, with its own routes, sessions, and configuration, and run in parallel with the others.
Running a command
Once the application is built, laravel.Run makes your application's logger the default slog logger, and copies the variables from your .env file into the process's environment, so a library that reads the environment itself sees them too. Then it reads the command name from the command line.
With no command name, laravel.Run runs serve, which serves your application on 127.0.0.1:8000 by default. When you name a console command, such as laravel route:list or one your application defines, laravel.Run runs that command instead, with the same configuration, database, and services.
Handling a request
The kernel
Every request first enters Laravel's HTTP kernel. Go's HTTP server calls your application with a standard *http.Request, and the kernel wraps it in a web.Request. The kernel reads the visitor's address and scheme from the X-Forwarded-* headers only when the request came through a trusted proxy. It gives the request a request ID for your logs, and drops a trailing slash from the path, so /users/ reaches the route for /users. It also puts the application in the request's context, so the code you pass r to reaches your configuration, database, and services.
If your application has a health route, such as /up, the kernel answers it at this point, before any middleware runs.
Global middleware and routing
Next, the request passes through the global middleware, which run on every request. They add security headers, reject hosts your application doesn't serve, answer CORS requests, and trim the strings in form input. They run before routing, so method spoofing can turn an HTML form's POST into the PUT or DELETE your route expects.
Then the router finds the route that matches the request. If routes match the path but none of them accepts the request's method, the response is a 405. If no route matches at all, Laravel serves the matching file from public/. If no file matches either, your fallback route handles the request, or the response is a 404.
The route
Once Laravel has the route, the route's timeout starts, and the request runs through the route's middleware, then its handler:
- The route file's middleware group. Routes in
routes/web.gorun the middleware in thewebmiddleware group, which decrypt cookies, start the session, and check the CSRF token. Your application also adds session authentication and the Inertia middleware to thewebgroup inbootstrap/app.go. Routes inroutes/api.gorun theapimiddleware group instead, which has no middleware until you add some, so API routes have no session or cookies. - The route's own middleware. These are the middleware you assign to the route or to a route group that contains it, such as
auth.Authenticate. - The handler. Laravel reads the request's body first, so a body that's malformed or too large fails before your code sees it. Then your handler does your application's work and returns a
*web.Response.
Sending the response
The response travels back out through the route's middleware in reverse order, so each one may inspect or change its status, headers, and cookies. When a handler returns web.Fail(err) or panics, Laravel renders the error as a response first. The route's middleware then see an ordinary response, such as a 404 or 500 page, the same as when the handler succeeds.
If a middleware fails or panics instead, Laravel turns that into an error response too. One failing request never takes down the server.
Once the outermost middleware returns, the kernel writes the response. The session has been saved by then, so a streamed response or a file starts sending only after that. Finally, the kernel runs the functions the handler registered with r.OnFinish, and logs the request with its status and duration.
Shutting down
When the server receives SIGTERM, or you press Ctrl+C, it stops accepting new connections, closes open event streams, and waits up to SERVER_SHUTDOWN_TIMEOUT (20 seconds by default) for requests, ticks, and background work to finish before running ticks marked RunOnShutdown. To learn more, check out the deployment guide's section on stopping gracefully.
Where your startup code goes
Packages take part in each step above through their Register method, which adds their routes, middleware, services, and commands, and can check their setup when the application starts. Your application doesn't need a package of its own, because the options in bootstrap/app.go have the same hooks, such as Configure, Register, Middleware, and Services, and Laravel always applies them after every package. Put your application's own startup code there.
If you write a Laravel package that you want to publish and share with the community, you'll implement Register to read the package's settings from the environment, add its routes, middleware, and commands, and do anything else your application would do in bootstrap/app.go. The package development guide shows you how.