Skip to the workspace
Pebellslearn by building
Routing  ›  Lesson

Route Parameters

Route parameters 12 minCurly-brace segments in a URI capture values that are passed to the route's action in order, optional ones need a ? and a default, and where constraints limit what they match.

laravel / Route Parameters

Explore each scene at your own pace.

01 · The rule

The rule

Route Parameters

Lendly has 500 books. Writing 500 routes, one for /books/1, one for /books/2 and so on, is absurd. You want one route that means "/books/ followed by any id", with the id handed to your code. That is a route parameter.

The rule

Braces capture a segment; the closure receives it in order.

Route::get('/books/{id}', function (string $id) {
    return "Book number {$id}";
});

A visit to /books/42 runs the closure with $id = '42'.

With several parameters, they are passed in the order they appear in the URI. The variable names in the closure do not have to match:

Route::get('/members/{member}/loans/{loan}', function ($m, $l) {
    return "Loan {$l} of member {$m}";
});

Optional parameters use a ? in the URI and need a default value in the closure:

Route::get('/members/{name?}', function (?string $name = 'guest') {
    return "Hello, {$name}";
});

/members gives "Hello, guest", and /members/ana gives "Hello, ana".

Constraints limit what a parameter may be. If the value does not fit, the route does not match, and the visitor gets a 404:

Route::get('/books/{id}', fn ($id) => "Book {$id}")
    ->whereNumber('id');

Route::get('/genres/{slug}', fn ($slug) => $slug)
    ->where('slug', '[a-z-]+');

Other helpers include whereAlpha, whereAlphaNumeric, whereUuid and whereIn('status', ['open', 'returned']).

By default a parameter matches anything except /.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.