Route model binding and compile-checked URLs
Part 2 · Laravel Rust. Let Laravel load a menu item straight from the URL (or return a 404), and build links with route! and redirect! that the compiler checks.
In the last lesson, /orders/42 gave your handler the number 42. But a number isn’t what you actually want. You want order 42 itself: its items, its total, its customer. And if there is no order 42, the customer should see a “not found” page.
Laravel Rust does that work for you with route model binding. In this lesson you’ll use it for the café’s menu pages. Then you’ll learn to build links with the route! and redirect! macros, which the compiler checks so your links can’t quietly break. This lesson follows the official routing guide (opens in new tab), models guide (opens in new tab) and URL generation guide (opens in new tab).
A quick model, just for this lesson
A model is a Rust struct that stands for one database table. Each field is a column, and each value of the struct is one row. You’ll learn models properly in Models and relationships. For now, here’s a small one for the café’s menu:
use laravel::model::model;use laravel::time::Timestamp;
#[model]pub struct MenuItem { pub id: i64, pub name: String, pub slug: String, pub price_cents: i64, pub created_at: Timestamp, pub updated_at: Timestamp,}#[model]is an attribute macro that turns this struct into a model. By convention it reads themenu_itemstable: the struct name in snake case, made plural.idis the primary key, the unique number that identifies each row. It’s ani64, not theu64you parsed withParams<u64>in the last lesson, because database integer columns are signed. With route model binding you never parse the id yourself, so the difference won’t trip you up.slugis a URL-friendly name, such asflat-white.price_centsusesi64, the integer type Laravel’s own model examples use for number columns. We still store whole cents, never fractions.
Note
To actually run this code you need a menu_items table, which you’ll create in Migrations and the schema builder. For now, focus on how routes and handlers use the model.
The long way: look it up yourself
Without route model binding, a handler gets the ID and does the rest itself: query the database, check whether a row came back, and return a 404 if not. That’s three steps of boilerplate, repeated in every handler that shows, edits or deletes something. It’s like a barista who has to walk to the storeroom and check the shelf before every single order.
Route model binding
Instead, ask for the model itself as a handler argument:
route.get("/menu/{menu_item}", menu::show);use laravel::prelude::*;
use crate::models::MenuItem;
pub async fn show(item: MenuItem) -> String { format!( "{}: ${}.{:02}", item.name, item.price_cents / 100, item.price_cents % 100 )}Here’s what happens when a request arrives:
- A customer visits
/menu/2. - Laravel sees that
showwants aMenuItemand that the route has a{menu_item}parameter. - Before calling
show, Laravel loads the menu item whoseidis2from the database. - If it exists,
showruns with the item already loaded. If not, Laravel responds with a404andshownever runs.
GET /menu/2 → Flat White: $4.00GET /menu/999 → 404 Not Found (no such item)GET /menu/latte → 404 Not Found ("latte" isn't a valid id)Your handler only has to cover the case where the item exists. Laravel covers the rest. This works with closures too, as the routing guide (opens in new tab) shows:
route.get("/menu/{menu_item}", async |item: MenuItem| item.name);Warning
The parameter name has to match the model’s name in snake case: {menu_item} for MenuItem, {order} for Order. The argument name (item above) can be anything. If you write /menu/{item} instead, Laravel won’t connect that parameter to your MenuItem.
Finding a model by another column
IDs make ugly URLs. /menu/flat-white reads better than /menu/2. To look a model up by a different column, add it after a colon:
route.get("/drinks/{menu_item:slug}", menu::show);The handler stays the same, show(item: MenuItem). Laravel now runs “find the menu item whose slug is flat-white” and still returns a 404 if there’s none. If every route should use the slug, you can set it once on the model instead, with #[model(route_key = "slug")].
Links: why strings break
Your pages need links to each other. The menu links to each item, and the order form sends customers to their receipt. The obvious way is to build a string:
let link = format!("/menu/{}", item.id);This works until the day you rename /menu to /drinks. Every format! that builds /menu/... still compiles and still runs, but now produces a link to a page that no longer exists. Customers get 404s, and you only find out when someone complains. Strings are like handwritten directions taped to the café door: if you move the counter, nobody updates the note.
route!: links to handlers, not paths
Laravel Rust links to a route by its handler, the function you registered it with. Pass the handler to the route! macro (it’s in the prelude):
let url = route!(menu::show, &item)?; // "http://127.0.0.1:8000/menu/2"menu::shownames the handler, not the path. Laravel looks up the route registered with it.&itemfills in the{menu_item}parameter. When you pass a model, Laravel uses its route key: theid, or the slug on a{menu_item:slug}route.route!returns alaravel::Result, because the handler might not be registered on any route. In a handler,?turns that failure into an error response, as you saw in Error handling with ?.
Now rename /menu/{menu_item} to /drinks/{menu_item} in web.rs, and every route!(menu::show, ...) produces the new URL automatically. No search-and-replace needed.
Here’s a JSON handler that includes each item’s own link, adapted from the URL generation guide (opens in new tab):
use laravel::prelude::*;use serde_json::{Value, json};
use crate::models::MenuItem;
pub async fn details(item: MenuItem) -> laravel::Result<Json<Value>> { Ok(Json(json!({ "name": item.name, "price_cents": item.price_cents, "url": route!(show, &item)?, })))}You can also pass extra values by name. Names that don’t match a placeholder become the query string:
route!(menu::index, page = 2)?; // "http://127.0.0.1:8000/menu?page=2"redirect!: send the customer somewhere else
A redirect is a response that says “go to this other URL instead.” Browsers follow it automatically. The redirect! macro takes the same arguments as route!, but returns a Redirect response.
The café puts a “Today’s special” button on its home page. Instead of building a special page, it redirects to the item’s normal page:
pub async fn special() -> Redirect { redirect!(show, 3).with_query([("size", "large")])}showis the handler in this same module, so the module prefix isn’t needed.3fills{menu_item}with a raw ID. You can pass a model like&iteminstead..with_query(...)adds?size=large, so the customer lands on/menu/3?size=large.
In Typed validation and forms you’ll see the most common use: after saving a submitted form, a handler ends with something like Ok(redirect!(show, &order)) to send the customer to their new order’s page.
The compiler has your back
Here’s the best part. Say you rename the handler menu::show to menu::item_page but forget about a redirect!(menu::show, &item) elsewhere. With string URLs, that mistake would reach customers. With redirect!, the app doesn’t compile. You’ll get an error roughly like this (exact wording can differ):
error[E0425]: cannot find function `show` in module `menu` --> src/http/handlers/orders.rs:14:24 |14 | Ok(redirect!(menu::show, &item)) | ^^^^ not found in `menu`Read it top to bottom: what went wrong (cannot find function show), then the file and line (orders.rs:14), then a ^^^^ pointing at the exact spot. Fix the name and it compiles again. The official docs put it this way: “If you rename or remove a handler, the compiler shows you every route! and redirect! call that still uses it.”
Tip
To link from an HTML template rather than Rust code, pass the handler’s path as text: {{ route("menu::show", item) }}. The templates guide (opens in new tab) covers it.
Try it yourself
- The café has an
Ordermodel (with anidkey). Write the route and ashowhandler inorders.rsso that/orders/7returns"Order #7"when the order exists, and a404when it doesn’t. - Write a handler
orders::latest_receiptthat always redirects to order7’s page (pretend that’s the latest), adding?print=1to the URL.
Show solution
route.get("/orders/{order}", orders::show);route.get("/orders/latest/receipt", orders::latest_receipt);use laravel::prelude::*;
use crate::models::Order;
pub async fn show(order: Order) -> String { format!("Order #{}", order.id)}
pub async fn latest_receipt() -> Redirect { redirect!(show, 7).with_query([("print", "1")])}The parameter is named {order} because the model is Order. A missing order never reaches show, because Laravel answers with a 404 first. /orders/latest/receipt doesn’t clash with /orders/{order}, because it has more segments (and latest would fail to parse as an ID anyway).
Recap
- Route model binding: take a model like
item: MenuItemas a handler argument and Laravel loads it from the URL, or returns a404before your handler runs. - The route parameter must match the model name in snake case (
{menu_item}). Use{menu_item:slug}to look it up by another column. route!(handler, params)?builds a URL from a handler, not a hard-coded path, andredirect!builds a redirect the same way.- Pass models (
&item) as parameters, and named extras become query strings. - If you rename or remove a handler, the compiler points out every link that still uses it.
What’s next
You’ve finished Meet Laravel Rust! Next you’ll build the café’s real database tables in Migrations and the schema builder, the first lesson of the data module.
0 of 35 lessons complete