Laravel Route Parameters

Laravel Route Parameters

Route parameters let you capture segments of the URI and pass them to your route handler or controller.

1 - Required Parameters

// routes/web.php
Route::get('/user/{id}', function (string $id) {
    return 'User ' . $id;
});

Route::get('/post/{id}/comment/{commentId}', function (string $id, string $commentId) {
    return "Post $id, Comment $commentId";
});

2 - Optional Parameters

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

// Matches /user  → Hello, Guest
// Matches /user/Alice → Hello, Alice

3 - Parameter Constraints

// Only match numeric IDs
Route::get('/user/{id}', function (string $id) {
    return $id;
})->where('id', '[0-9]+');

// Shorthand helpers
Route::get('/user/{id}', fn ($id) => $id)->whereNumber('id');
Route::get('/search/{term}', fn ($t) => $t)->whereAlphaNumeric('term');

4 - Accessing Parameters in Controllers

// Route definition
Route::get('/article/{slug}', [ArticleController::class, 'show']);

// Controller
public function show(string $slug): View
{
    $article = Article::where('slug', $slug)->firstOrFail();
    return view('articles.show', compact('article'));
}

Note: Route model binding lets Laravel automatically resolve Eloquent models from route parameters. Replace string $slug with Article $article and Laravel does the query for you.

-Tip-