Handlers
Introduction
Instead of writing all of your request handling as function literals in your route files, you may organize it in handlers. A handler is a function that takes a request and returns a response, and related handlers live together in a package. For example, a posts package might hold the handlers that list, show, and create blog posts. Your application keeps these packages in the handlers directory.
Writing handlers
Basic handlers
A handler reads what it needs from the request and returns a response. For example, here's a posts package in handlers/posts/posts.go. Its Index handler lists every post, Show displays a single post, and Store creates a post from a submitted form:
1package posts23import (4 "go.laravel.com/inertia"5 "go.laravel.com/model"6 "go.laravel.com/validation"7 "go.laravel.com/validation/rule"8 "go.laravel.com/web"910 "app/models"11)1213type NewPost struct {14 Title string `json:"title"`15 Body string `json:"body"`16}1718func (f *NewPost) Rules() validation.Rules {19 return validation.For(f,20 rule.Field(&f.Title, rule.Required, rule.Max(255)),21 rule.Field(&f.Body, rule.Required),22 )23}2425func Index(r *web.Request) *web.Response {26 posts, err := model.Query[models.Post]().Latest("created_at").Get(r)27 if err != nil {28 return web.Fail(err)29 }3031 return inertia.Render("Posts/Index", inertia.Props{"posts": posts})32}3334func Show(r *web.Request) *web.Response {35 post, err := model.FromRoute[models.Post](r, "post")36 if err != nil {37 return web.Fail(err)38 }3940 return inertia.Render("Posts/Show", inertia.Props{"post": post})41}4243func Store(r *web.Request) *web.Response {44 form, err := r.Validate[NewPost]()45 if err != nil {46 return web.Fail(err)47 }4849 post := models.Post{Title: form.Title, Body: form.Body}50 if err := model.Create(r, &post); err != nil {51 return web.Fail(err)52 }5354 return web.RedirectRoute("posts.show", "post", &post)55}1package posts23import (4 "go.laravel.com/inertia"5 "go.laravel.com/model"6 "go.laravel.com/validation"7 "go.laravel.com/validation/rule"8 "go.laravel.com/web"910 "app/models"11)1213type NewPost struct {14 Title string `json:"title"`15 Body string `json:"body"`16}1718func (f *NewPost) Rules() validation.Rules {19 return validation.For(f,20 rule.Field(&f.Title, rule.Required, rule.Max(255)),21 rule.Field(&f.Body, rule.Required),22 )23}2425func Index(r *web.Request) *web.Response {26 posts, err := model.Query[models.Post]().Latest("created_at").Get(r)27 if err != nil {28 return web.Fail(err)29 }3031 return inertia.Render("Posts/Index", inertia.Props{"posts": posts})32}3334func Show(r *web.Request) *web.Response {35 post, err := model.FromRoute[models.Post](r, "post")36 if err != nil {37 return web.Fail(err)38 }3940 return inertia.Render("Posts/Show", inertia.Props{"post": post})41}4243func Store(r *web.Request) *web.Response {44 form, err := r.Validate[NewPost]()45 if err != nil {46 return web.Fail(err)47 }4849 post := models.Post{Title: form.Title, Body: form.Body}50 if err := model.Create(r, &post); err != nil {51 return web.Fail(err)52 }5354 return web.RedirectRoute("posts.show", "post", &post)55}
Each handler reads only what it needs from the request:
Showfinds the post that the route's path names, such as post 42 for/posts/42. If no post has that ID,model.FromRoutereturns an error, andweb.Failresponds with a404page.Storevalidates the form's input into aNewPost. If the input is invalid,web.Failsends the user back to the form with the errors. Otherwise,Storecreates the post and redirects to the new post's page.
When a handler gets an error back, such as from a failed database query, it returns web.Fail(err). Laravel renders the error as a response, such as an error page, and reports it when it's a server error. If a handler needs to answer with a status of its own, such as a 403 for a user who may not see a post, it returns web.Abort(http.StatusForbidden). To learn more, check out the error handling guide's section on HTTP errors.
Handlers and routes
Once you've written a handler, point a route at it in a route file, such as routes/web.go. When a request matches the route's path, Laravel reads the request's body and calls the handler:
1package routes23import (4 "go.laravel.com/config"5 "go.laravel.com/routing"67 "app/handlers/posts"8)910func Web(route *routing.Router, cfg *config.Config) {11 route.Get("/posts", posts.Index).Name("posts.index")12 route.Get("/posts/{post}", posts.Show).Name("posts.show")13 route.Post("/posts", posts.Store).Name("posts.store")14}1package routes23import (4 "go.laravel.com/config"5 "go.laravel.com/routing"67 "app/handlers/posts"8)910func Web(route *routing.Router, cfg *config.Config) {11 route.Get("/posts", posts.Index).Name("posts.index")12 route.Get("/posts/{post}", posts.Show).Name("posts.show")13 route.Post("/posts", posts.Store).Name("posts.store")14}
A route's name lets the rest of your application link to it without repeating its path. For example, urls.Route(r, "posts.show", "post", &post) returns the post's URL, such as http://example.com/posts/42. To learn more, check out the routing guide's section on named routes.
Some handlers should only run for certain users, such as a handler that creates posts, which only logged-in users should reach. To check the request before the handler runs, attach a middleware to the handler's route. For example, auth.Authenticate redirects guests to your login page:
1import "go.laravel.com/auth"23route.Post("/posts", posts.Store).Name("posts.store").Middleware(auth.Authenticate{})1import "go.laravel.com/auth"23route.Post("/posts", posts.Store).Name("posts.store").Middleware(auth.Authenticate{})
Many packages hold the same set of handlers: Index, Create, Store, Show, Edit, Update, and Destroy, which list, create, show, change, and delete a model. Rather than register a route for each of them, you may register them all at once with route.Resource. To learn more, check out the routing guide's section on resource routes.
Reading the request
Every handler has the same signature, func(r *web.Request) *web.Response, and reads what it needs from r. The request embeds Go's *http.Request, so r.Header, r.URL, and r.PathValue are the standard ones you already know. The request is also a context, so pass r to anything that waits, such as a database query. Then the query stops when the request ends, such as when the visitor closes the page.
These are the calls handlers make most often:
| Call | What it returns |
|---|---|
model.FromRoute[models.Post](r, |
The model that the route parameter names, or an error that responds with a 404. |
r.User[models.User]() |
The logged-in user, or nil for a guest. |
r.Validate[NewPost]() |
The request's body input, validated into your struct. |
r.Query[PostFilters]() |
The request's query string, parsed into your struct. |
r.PathValue("post") |
A route parameter, as a string. |
r.Session() |
The request's session, on routes in the web group. |
services.From(r) |
Your application's services. |
Laravel reads the request's body before your handler runs, so a body that's malformed or too large fails before your code sees it. A handler may then read the user, the route's model, and the input in any order, and as often as it likes. For example, this handler, on a route behind auth.Authenticate, updates the logged-in user's profile from a validated form, then sends them back to the page they came from:
1package profile23import (4 "go.laravel.com/db"5 "go.laravel.com/model"6 "go.laravel.com/validation"7 "go.laravel.com/validation/rule"8 "go.laravel.com/web"910 "app/models"11)1213type EditProfile struct {14 Name string `json:"name"`15}1617func (f *EditProfile) Rules() validation.Rules {18 return validation.For(f,19 rule.Field(&f.Name, rule.Required, rule.Max(255)),20 )21}2223func Update(r *web.Request) *web.Response {24 user := r.User[models.User]()2526 form, err := r.Validate[EditProfile]()27 if err != nil {28 return web.Fail(err)29 }3031 if err := model.Update(r, user, db.Values{"name": form.Name}); err != nil {32 return web.Fail(err)33 }3435 return web.Back()36}1package profile23import (4 "go.laravel.com/db"5 "go.laravel.com/model"6 "go.laravel.com/validation"7 "go.laravel.com/validation/rule"8 "go.laravel.com/web"910 "app/models"11)1213type EditProfile struct {14 Name string `json:"name"`15}1617func (f *EditProfile) Rules() validation.Rules {18 return validation.For(f,19 rule.Field(&f.Name, rule.Required, rule.Max(255)),20 )21}2223func Update(r *web.Request) *web.Response {24 user := r.User[models.User]()2526 form, err := r.Validate[EditProfile]()27 if err != nil {28 return web.Fail(err)29 }3031 if err := model.Update(r, user, db.Values{"name": form.Name}); err != nil {32 return web.Fail(err)33 }3435 return web.Back()36}
Because the request embeds *http.Request, you may also call its standard methods, such as r.FormValue. However, prefer r.Validate and the input methods above to r.FormValue and to decoding r.Body yourself. The standard methods return an empty value or an error your handler must turn into a response, so a user with invalid input never sees what went wrong. With r.Validate, a form gets its errors back after a redirect, and a JSON client gets them as JSON.
Handlers with dependencies
Many handlers need something that lives longer than a request, such as a payment provider's client or a search index. These are your application's services. Laravel builds them from your settings when your application starts, and a handler reaches them with services.From(r). For example, this handler lists the user's invoices from your billing service:
1package invoices23import (4 "go.laravel.com/web"56 "app/services"7)89func Index(r *web.Request) *web.Response {10 invoices, err := services.From(r).Billing.Invoices(r)11 if err != nil {12 return web.Fail(err)13 }1415 return web.JSON(invoices)16}1package invoices23import (4 "go.laravel.com/web"56 "app/services"7)89func Index(r *web.Request) *web.Response {10 invoices, err := services.From(r).Billing.Invoices(r)11 if err != nil {12 return web.Fail(err)13 }1415 return web.JSON(invoices)16}
Middleware call services.From(r) too, on the request they receive. Functions below your handlers take a ctx context.Context and call services.From(ctx), so they work from a job or a command too. A package's services come from the package instead, such as inspire.From(r). To learn more, check out the packages guide's section on services.
In a test, you may replace one service with a fake, such as a billing client that never charges a card. Each application your tests build has its own services, so you have nothing to swap back afterward. To learn how, check out the testing guide's section on replacing dependencies.
A value that belongs to a single request, such as the logged-in user, isn't a service. The request's context carries it instead. If you'd like a middleware to add a value of your own, such as the team that a subdomain names, check out the context guide's section on adding values of your own.
Standard handlers
Much of Go's ecosystem is written for net/http, and many libraries give you an http.Handler, such as a Prometheus metrics endpoint or a reverse proxy. To serve one from your application, mount it with route.Handle. The handler then answers every method on its path:
1import (2 "github.com/prometheus/client_golang/prometheus/promhttp"34 "go.laravel.com/config"5 "go.laravel.com/routing"6)78func Web(route *routing.Router, cfg *config.Config) {9 route.Handle("/metrics", promhttp.Handler())10}1import (2 "github.com/prometheus/client_golang/prometheus/promhttp"34 "go.laravel.com/config"5 "go.laravel.com/routing"6)78func Web(route *routing.Router, cfg *config.Config) {9 route.Handle("/metrics", promhttp.Handler())10}
The route still runs its middleware, so you may put a standard handler behind auth.Authenticate. Laravel leaves the request's body unread, so the standard handler can read the body itself.
To mount a standard handler for one method, start the pattern with the method, as you would for an http.ServeMux. For example, a payment provider's library might give you a webhook handler for its POST requests:
1route.Handle("POST /webhooks/stripe", webhook)1route.Handle("POST /webhooks/stripe", webhook)
Use route.Handle rather than route.Post for a standard handler, because a route.Post route reads a form's body before its handler runs. If you'd like to use standard middleware too, check out the middleware guide's section on standard middleware.
Your application is itself an http.Handler. So you may serve the value that laravel.New returns with your own http.Server, or mount your application inside a larger program.