Routing in Laravel Rust, for Laravel developers
Route files, handlers, typed parameters and route model binding, shown on a concert-ticketing site and compared with the Route facade you know.
- routing
- handlers
Routing in Laravel Rust works the way routes/web.php does: a list of URIs, each pointing at the code that handles it. What changes is how much the compiler checks before anything runs.
To keep it concrete, picture a concert-ticketing site. It lists upcoming shows, has a page per concert with a seat map, lets fans hold seats while they pay, and lets them browse by genre.
Two route files, two groups
Routes are plain Rust functions in src/routes/, registered in the with_routing call in src/app.rs. The split mirrors Laravel PHP:
webroutes (src/routes/web.rs) run with sessions, encrypted cookies and CSRF protection. The seat map and checkout live here.apiroutes (src/routes/api.rs) are stateless and sit under/api, which suits a mobile app scanning tickets at the door. Call.api_prefix(...)to version them, for example under/api/v1.
The ticketing site’s routes
// src/routes/web.rs
use laravel::prelude::*;
use crate::http::handlers::{concerts, genres, seats};
pub fn routes(route: &mut Router) {
route.get("/box-office", async || "Box office opens at 10:00");
route.get("/concerts", concerts::index);
route.get("/concerts/page/{number}", concerts::page);
route.get("/concerts/{concert}", concerts::show);
route.get("/concerts/{concert}/seats", seats::index);
route.post("/concerts/{concert}/holds", seats::hold);
route.get("/genre/{genre}", genres::show);
}
The box-office line answers straight from a closure, which is fine for something that small. Everything else points at a handler: an async function, grouped by resource under src/http/handlers/. Handlers do the job controller methods do in PHP.
There’s a method for each HTTP verb (get, post, put, patch, delete, options). Use on to accept several verbs, or any to accept all of them.
How a request finds its handler
Parameters arrive typed
The Params extractor parses each URI segment into the type you ask for. Paging through upcoming shows:
// src/http/handlers/concerts.rs
use laravel::prelude::*;
pub async fn page(Params(number): Params<u32>) -> String {
format!("Upcoming concerts, page {number}")
}
Tip: the type is the validation.
/concerts/page/twocan’t become au32, so the visitor gets a404andpagenever runs. In PHP you’d add->whereNumber(); here the type does that job.
The same trick limits a segment to a fixed set of words. Genres are an enum:
// src/http/handlers/genres.rs
use laravel::prelude::*;
#[derive(Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Genre {
Rock,
Jazz,
Electronic,
Classical,
}
pub async fn show(Params(genre): Params<Genre>) -> &'static str {
match genre {
Genre::Rock => "Guitars, loud",
Genre::Jazz => "Late sets, small rooms",
Genre::Electronic => "Doors at midnight",
Genre::Classical => "Seated, programme included",
}
}
/genre/jazz works. /genre/polka is a 404. Add a genre to the enum and the compiler shows you every match that needs a new arm.
Optional segments use the ? you know, as in /{city?}, with an Option type on the Rust side.
Route model binding
Say Concert is a model with artist and venue columns. Ask for the model instead of its ID, and Laravel looks it up:
use crate::models::Concert;
pub async fn show(concert: Concert) -> String {
format!("{} at {}", concert.artist, concert.venue)
}
If there’s no concert with that key, maybe because the show was cancelled and removed, the fan gets a 404 before show runs. That’s the same as implicit binding in PHP.
For shareable URLs, look concerts up by another column with the syntax you already know: /tickets/{concert:slug} serves /tickets/summer-jazz-night.
Routes that only redirect or render
route.permanent_redirect("/shows/{concert}", "/concerts/{concert}");
route.redirect("/tickets", "/concerts");
route.view("/refund-policy", "refund-policy");
route.inertia("/venue-map", "VenueMap");
These match Route::permanentRedirect, Route::redirect, Route::view and Route::inertia in PHP.
Links without route names
You don’t name routes. You link through the handler itself, with route!, or redirect! when you want a redirect response:
let url = route!(concerts::show, concert.id)?;
Rename or remove concerts::show and every link to it stops compiling. The “Buy tickets” button in last month’s newsletter template can’t quietly point at a route that no longer exists.
Checking what you registered
laravel route:list --handler=concerts
Add -v to see each route’s middleware, --path= to filter by URI, or --json to feed the list to a script.
Quick reference
| Laravel PHP | Laravel Rust |
|---|---|
routes/web.php |
src/routes/web.rs |
| A controller method | A handler function in src/http/handlers/ |
->whereNumber('number') |
Params<u32> |
->whereIn('genre', [...]) |
Params<Genre> with an enum |
route('concerts.show', $id) |
route!(concerts::show, id)? |