Handlers
Introduction
Instead of writing all of your request handling as closures in your route files, you may organize it in handlers. A handler is an async function that handles a request, and related handlers live together in a module. For example, a posts module might hold the handlers that list, show, and create blog posts. Your application keeps these modules in the src/http/handlers directory.
Writing handlers
Basic handlers
A handler asks for what it needs through its arguments, and returns a response. For example, here's a posts module in src/http/handlers/posts.rs. Its index handler lists every post, show displays a single post, and store creates a post from a submitted form:
1use laravel::inertia::{self, Page, props};2use laravel::model::create;3use laravel::prelude::*;45use crate::models::Post;67#[laravel::input(fills = Post)]8#[validate(authenticated)]9pub struct NewPost {10 #[validate(required, max_length(255))]11 pub title: String,12 #[validate(required)]13 pub body: String,14}1516pub async fn index() -> laravel::Result<Page> {17 let posts = Post::all().await?;1819 Ok(inertia::render("Posts/Index", props! { posts }))20}2122pub async fn show(post: Post) -> Page {23 inertia::render("Posts/Show", props! { post })24}2526pub async fn store(Valid(input): Valid<NewPost>) -> laravel::Result<Redirect> {27 let post = create!(Post { ..input }).await?;2829 Ok(redirect!(show, &post))30}1use laravel::inertia::{self, Page, props};2use laravel::model::create;3use laravel::prelude::*;45use crate::models::Post;67#[laravel::input(fills = Post)]8#[validate(authenticated)]9pub struct NewPost {10 #[validate(required, max_length(255))]11 pub title: String,12 #[validate(required)]13 pub body: String,14}1516pub async fn index() -> laravel::Result<Page> {17 let posts = Post::all().await?;1819 Ok(inertia::render("Posts/Index", props! { posts }))20}2122pub async fn show(post: Post) -> Page {23 inertia::render("Posts/Show", props! { post })24}2526pub async fn store(Valid(input): Valid<NewPost>) -> laravel::Result<Redirect> {27 let post = create!(Post { ..input }).await?;2829 Ok(redirect!(show, &post))30}
Each handler takes only the arguments it needs, and Laravel provides them when the request comes in:
showtakes the post that the route's URI names, such as post 42 for/posts/42. If no post has that ID, Laravel responds with a404page, andshownever runs.storetakes the form's input after it has been validated. If the input is invalid, Laravel sends the user back to the form with the errors. Otherwise,storecreates the post and redirects to the new post's page.
Each handler returns a laravel::Result, so it may use ? on any error. When a handler returns an error, Laravel renders the error as a response, such as an error page.
Once you've written a module, declare it in src/http/handlers/mod.rs, so your route files can use its handlers:
1pub mod posts;1pub mod posts;
Handlers and routes
Once you've written a handler, point a route at it in a route file, such as src/routes/web.rs. When a request matches the route's URI, Laravel builds the handler's arguments from the request and calls the handler:
1use laravel::prelude::*;23use crate::http::handlers::posts;45pub fn routes(route: &mut Router) {6 route.get("/posts", posts::index);7 route.get("/posts/{post}", posts::show);8 route.post("/posts", posts::store);9}1use laravel::prelude::*;23use crate::http::handlers::posts;45pub fn routes(route: &mut Router) {6 route.get("/posts", posts::index);7 route.get("/posts/{post}", posts::show);8 route.post("/posts", posts::store);9}
Since each route is identified by its handler, you link to a route by naming its handler. For example, route!(posts::show, &post)? returns the post's URL, such as http://example.com/posts/42. To learn more, check out the routing guide's section on linking to 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, Authenticate redirects guests to your login page:
1use laravel::auth::Authenticate;23route.post("/posts", posts::store).middleware(Authenticate);1use laravel::auth::Authenticate;23route.post("/posts", posts::store).middleware(Authenticate);
Many modules 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 resource!(posts). To learn more, check out the routing guide's section on resource routes.
Handler arguments
A handler may take any number of arguments. Each argument is an extractor: a type that Laravel builds from the request before it calls your handler. If Laravel can't build an argument, it responds without calling the handler. For example, it responds with a 404 when a post doesn't exist, and redirects back to the form when the input is invalid.
These are the arguments handlers take most often:
| Argument | What it is |
|---|---|
A model, such as Post |
The model that the route parameter named after it finds. |
Authenticated<User> |
The logged-in user. It redirects guests to your login page. |
Auth<User> |
The authentication state, for logging users in and out, and for pages that guests see too. |
Valid<T> |
The request's input, validated into T. |
Query<T> |
The query string, parsed into a #[laravel::query] struct T. |
Request |
The request, with its input, its session through request.session(), and the logged-in user through request.user(). |
Session |
The request's session, on routes in the web group. |
Params<T> |
The route parameters. |
Inject<T> |
A service from the container. |
Section<T> |
One of your own configuration sections. |
Inertia |
The request's Inertia state, for page options beyond inertia::render. |
Valid<T> and Request both read the request's body, and a body can only be read once. So a handler may take only one of them, and it must be the handler's last argument. For example, this handler updates the logged-in user's profile. It takes the user first and the validated form last:
1use laravel::model::update;2use laravel::prelude::*;34use crate::models::User;56#[laravel::input(fills = User)]7#[validate(authenticated)]8pub struct EditProfile {9 #[validate(required, max_length(255))]10 pub name: String,11}1213pub async fn update(14 Authenticated(mut user): Authenticated<User>,15 Valid(input): Valid<EditProfile>,16) -> laravel::Result<Redirect> {17 update!(user { ..input }).await?;1819 Ok(Redirect::back())20}1use laravel::model::update;2use laravel::prelude::*;34use crate::models::User;56#[laravel::input(fills = User)]7#[validate(authenticated)]8pub struct EditProfile {9 #[validate(required, max_length(255))]10 pub name: String,11}1213pub async fn update(14 Authenticated(mut user): Authenticated<User>,15 Valid(input): Valid<EditProfile>,16) -> laravel::Result<Redirect> {17 update!(user { ..input }).await?;1819 Ok(Redirect::back())20}
A handler may also take any Axum extractor. However, prefer Laravel's Query<T> and Valid<T> to Axum's Query and Form extractors. When the input is invalid, Axum's Query and Form respond with plain text and skip your application's error handling, so the user never sees their errors. With Laravel's Query<T>, Valid<T>, and Request::parse, forms get their errors back after a redirect, JSON clients get structured JSON errors, and query structs drop bad optional filters cleanly.
When a function can't handle requests
If a route's handler takes an argument Laravel can't build, or takes its arguments in the wrong order, the route fails to compile with the error "this function can't handle requests". The usual cause is an argument that reads the body, such as Request, placed before another argument. The error doesn't say which argument is wrong, so add #[debug_handler] to the handler to find out:
1use laravel::prelude::*;2use laravel::routing::debug_handler;34#[debug_handler]5pub async fn update(request: Request, session: Session) -> Redirect {6 // Save the form, then redirect...7 todo!()8}1use laravel::prelude::*;2use laravel::routing::debug_handler;34#[debug_handler]5pub async fn update(request: Request, session: Session) -> Redirect {6 // Save the form, then redirect...7 todo!()8}
With #[debug_handler], the compiler points at Request and says it can't come before the last argument. To fix the handler, move request after session. You may leave #[debug_handler] in place, because it only adds checks at compile time.