Routing and handlers
Part 2 · Laravel Rust. Point URLs at code: write routes with closures, move them into handler modules, return text and JSON, and read route parameters.
A café needs a front door and someone behind the counter. In a Laravel Rust app, routes are the front door: they decide where each visitor goes. Handlers are the staff behind the counter: they take the request and hand back a response.
In this lesson you’ll give Rusty Bean Café its first pages: a greeting, a menu, a JSON price list and pages for individual orders. Everything here follows the official routing guide (opens in new tab) and handlers guide (opens in new tab).
What is a route?
A route is a rule that says: “when a request with this method arrives at this URI, run this code.” For example:
GET /menu: show the menu.POST /orders: someone submitted the order form, so save it.
When a request comes in, Laravel looks at its method and URI, finds the matching route and runs the code attached to it.
Your first route: a closure
Open src/routes/web.rs. Your app already has some routes in there. Add a greeting:
use laravel::prelude::*;
pub fn routes(route: &mut Router) { // ...the routes your app already has...
route.get("/hello", async || "Welcome to Rusty Bean Café!");}Step by step:
use laravel::prelude::*;is a glob import of Laravel’s prelude. It brings inRouterand other everyday types in one line (see Modules and crates for globs and preludes).pub fn routes(route: &mut Router)is the functionsrc/app.rsregisters as your web routes. Laravel calls it once at startup and lends it the router mutably, so you can add routes (that’s borrowing from Borrowing and references).route.get(...)registers a route forGETrequests to/hello.async || "Welcome to Rusty Bean Café!"is an async closure with no arguments. When the route matches, Laravel awaits it and sends the string back as plain text.
With laravel dev running, save the file, wait for the rebuild and visit http://127.0.0.1:8000/hello:
Welcome to Rusty Bean Café!Note
async || ... is an async closure, a closure that works like an async fn. It combines two things you already know: closures from Closures and iterators and async from Async/await and Tokio. Every route’s code is async, so it can wait on a database without blocking other customers.
One method per HTTP verb
The router has a method for each HTTP verb (another word for method):
route.get(uri, handler);route.post(uri, handler);route.put(uri, handler);route.patch(uri, handler);route.delete(uri, handler);route.options(uri, handler);You’ll use get for pages people look at and post for forms they submit. put, patch and delete are for changing and removing things.
Moving code into handlers
Closures are great for a quick page. But imagine fifty routes, each with ten lines of logic, all in web.rs. It would be like the whole café menu, recipes included, written on the front door.
So most routes point at a handler: an async fn in its own module under src/http/handlers/. The route file stays a short list of URLs, and each handler holds the code for one page.
Create a menu module:
use laravel::prelude::*;
pub async fn index() -> String { let items = ["Espresso", "Flat White", "Muffin"];
format!("Today's menu: {}", items.join(", "))}pub async fn index()is the handler.publets the route file use it.- It takes no arguments, because this page needs nothing from the request.
- It returns a
String, which Laravel sends back as plain text.
Then declare the module so Rust compiles it:
pub mod menu;And point a route at it:
use laravel::prelude::*;
use crate::http::handlers::menu;
pub fn routes(route: &mut Router) { route.get("/hello", async || "Welcome to Rusty Bean Café!"); route.get("/menu", menu::index);}Notice menu::index has no parentheses. You’re not calling the function, you’re handing Laravel the function itself so it can call it later for each request.
Visit /menu:
Today's menu: Espresso, Flat White, MuffinWarning
Forgot pub mod menu; in src/http/handlers/mod.rs? Then use crate::http::handlers::menu; fails to compile with an error like “unresolved import”. Every new handler file needs its mod line.
Returning different kinds of responses
A handler can return any type Laravel knows how to turn into a response (any type that implements IntoResponse). Here are the most useful ones.
JSON
A mobile app or a JavaScript widget wants data, not a sentence. For that, return JSON, a text format for structured data. Wrap any value that implements Serialize in Json:
use laravel::prelude::*;
#[derive(Serialize)]pub struct MenuEntry { pub name: &'static str, pub price_cents: u32,}
pub async fn prices() -> Json<Vec<MenuEntry>> { Json(vec![ MenuEntry { name: "Espresso", price_cents: 300 }, MenuEntry { name: "Flat White", price_cents: 400 }, ])}#[derive(Serialize)](an attribute, see Macros and attributes) teaches the struct how to become JSON.price_cents: u32stores money as whole cents, just like in our Rust lessons, so there are no rounding surprises.Json(...)wraps the vector. Laravel turns it into JSON and sets theContent-Typeheader toapplication/json, so clients know what they’re getting.
Register it with route.get("/menu/prices", menu::prices); and visit it:
[{"name":"Espresso","price_cents":300},{"name":"Flat White","price_cents":400}]A different status code
Every response has a status code, a number that sums up how things went: 200 means OK, 404 means “not found”. To send a different one, return a tuple of the code and the body:
use laravel::prelude::*;
pub async fn catering_request() -> (StatusCode, &'static str) { // Queue the request for the manager...
(StatusCode::ACCEPTED, "Thanks! We'll get back to you within a day.")}StatusCode::ACCEPTED is 202: “got it, we’ll deal with it later.” Laravel can also return HTML views, Inertia pages, redirects and file downloads. The responses guide (opens in new tab) lists them all.
Route parameters
The café wants a page for each order: /orders/1, /orders/2 and so on. You don’t write a route per order. Instead you write one route with a parameter, a placeholder in braces:
route.get("/orders/{order}", orders::show);The handler receives the parameter through the Params extractor. An extractor is a handler argument that Laravel builds from the request before calling your handler:
use laravel::prelude::*;
pub async fn show(Params(id): Params<u64>) -> String { format!("Order #{id} is being prepared ☕")}Params<u64>says “parse the route parameter as au64.”Params(id)is a destructuring pattern, like the ones from Enums and match. It unwraps the number intoid.
Why u64 here, when the database models in the next lesson use i64 ids? The official docs show both. Params<u64> only parses a number from the URL, and an unsigned type turns away negative numbers like /orders/-1 with a 404. Database integer columns are signed, so models store their ids as i64.
GET /orders/42 → Order #42 is being prepared ☕GET /orders/latte → 404 Not FoundIf the parameter doesn’t parse into its type, such as latte for a u64, the request gets a 404 and your handler never runs. The type is the rule.
Several parameters
With more than one parameter, ask for a tuple, in the order the URI names them:
// route: "/orders/{order}/items/{item}"pub async fn show_item(Params((order, item)): Params<(u64, u64)>) -> String { format!("Item {item} on order {order}")}An enum as a parameter
Because the type is the rule, an enum can limit a parameter to a fixed set of values. The café’s menu has three sections:
use laravel::prelude::*;
#[derive(Deserialize)]#[serde(rename_all = "lowercase")]pub enum Section { Coffee, Tea, Pastries,}
pub async fn section(Params(section): Params<Section>) -> &'static str { match section { Section::Coffee => "Espresso, Flat White, Cappuccino", Section::Tea => "Tea, Hot Chocolate", Section::Pastries => "Croissant, Muffin, Bagel, Cookie", }}#[derive(Deserialize)]lets Laravel build aSectionfrom the text in the URL.#[serde(rename_all = "lowercase")]means the URL usescoffee, notCoffee.matchhandles every section, and the compiler makes sure you didn’t forget one.
With route.get("/menu/sections/{section}", menu::section);, the URL /menu/sections/tea works and /menu/sections/sandwiches is a 404, without a single if in your code.
Tip
When several routes could match, a fixed segment wins over a parameter. In the next lesson you’ll add /menu/{menu_item}, and /menu/prices will still reach menu::prices, because prices is a fixed segment. Run laravel route:list to see all your routes at once.
A first look at middleware
Some pages should only be open to some people. Middleware is code that runs before (or after) a handler, like a host at the door checking reservations. Laravel ships with Authenticate, which sends guests to the login page:
use laravel::auth::Authenticate;
route.prefix("/staff").middleware(Authenticate).group(|route| { route.get("/", staff::dashboard);});prefix("/staff") puts /staff in front of every route in the group, and middleware(Authenticate) guards them all. The middleware guide (opens in new tab) goes much deeper.
Try it yourself
- Add a
GET /hoursroute using a closure that returns"Open daily 7am–6pm". - Add a handler
orders::statusfor/orders/{order}/statusthat returns JSON like{"order":42,"status":"ready"}. Use a struct with#[derive(Serialize)]and always return"ready"for now.
Show solution
route.get("/hours", async || "Open daily 7am–6pm");route.get("/orders/{order}/status", orders::status);use laravel::prelude::*;
#[derive(Serialize)]pub struct OrderStatus { pub order: u64, pub status: &'static str,}
pub async fn status(Params(order): Params<u64>) -> Json<OrderStatus> { Json(OrderStatus { order, status: "ready" })}/orders/42/status returns {"order":42,"status":"ready"}, and /orders/abc/status is a 404. Remember pub mod orders; in src/http/handlers/mod.rs, and use crate::http::handlers::orders; in web.rs.
Recap
- A route pairs an HTTP method and a URI with code:
route.get("/menu", menu::index). - Closures suit tiny pages. Handlers (async functions in
src/http/handlers/) keep larger apps tidy. Declare each module withpub mod. - Handlers can return a
String,Json<T>, a(StatusCode, body)tuple and more. {order}in a URI becomes a parameter, read withParams<T>. If it doesn’t parse intoT, the response is a404.- Middleware such as
Authenticateguards routes before handlers run.
What’s next
Reading an order ID is nice, but you really want the order itself. In Route model binding and URLs Laravel loads database records straight from the URL, and you’ll generate links the compiler can check.
0 of 35 lessons complete