Laravel Routing: Route Parameters

Route Parameters

Are always encased within {} braces and should consist of alphabetic characters, and may not contain a - character. Instead of using the - character, use an underscore (_).

Are injected into route callbacks / controllers based on their order - the names of the callback / controller arguments do not matter.

Required Parameters

Syntax

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

Syntax

Route::get('posts/{post}/comments/{comment}', function ($postId, $commentId) {
    //
});

Optional Parameters

Syntax

Route::get('user/{name?}', function ($name = null) {
    return $name;
});

Route::get('user/{name?}', function ($name = 'John') {
    return $name;
});

Regular Expression Constraints

Syntax

Route::get('user/{name}', function ($name) {
    //
})->where('name', '[A-Za-z]+');

Route::get('user/{id}', function ($id) {
    //
})->where('id', '[0-9]+');

Route::get('user/{id}/{name}', function ($id, $name) {
    //
})->where(['id' => '[0-9]+', 'name' => '[a-z]+']);

Named Routes

Allow the convenient generation of URLs or redirects for specific routes.

Route::get('user/profile', function () {
    //
})->name('profile');
Route::get('user/profile', 'UserProfileController@show')->name('profile');

Laravel Routing: Route Parameters — Structure map

Clickable & Draggable!

Laravel Routing: Route Parameters — Related pages: