How to define a route with parameters?

In Laravel, you can pass values inside the URL using route parameters.

These parameters can be used inside your function to get dynamic data.

Example:

Route::get('/user/{id}', function ($id) {
    return "User ID: " . $id;
});

What happens here:

If you visit /user/5, it will show:

User ID: 5


Multiple Parameters

Route::get('/post/{category}/{id}', function ($category, $id) {
    return "Category: $category, Post ID: $id";
});

Visiting /post/tech/101 will show:

Category: tech, Post ID: 101


Optional Parameters

Route::get('/product/{name?}', function ($name = 'Default Product') {
    return $name;
});

Visiting /product → shows Default Product

Visiting /product/Phone → shows Phone


Route Parameters in Controllers

Route::get('/user/{id}', [UserController::class, 'show']);

In your UserController:

public function show($id) {
    return "User ID: " . $id;
}

Quick Tip:

  • {parameter} → Required
  • {parameter?} → Optional
  • Always use meaningful names for parameters.
Comments