Laravel for Beginners – Learn to Build Full-Stack Web Apps

Loading video...

Named Routes with Parameters

Routing

Named route with parameter

Route::get("/{lang}/product/{id}", function(string $lang, string $id) {
    // ...
})->name("product.view");

If we want to generate routes without route name

$productId = 123;
$lang = "en";
$productViewUrl = "/$lang/product/$productId";

Generate route with route name.

$productId = 123;
$lang = "en";
$productViewUrl = route("product.view", ["lang" => $lang, "id" => $productId]);

From the first look you see that you actually write more code, but it has great benefits. If you update your URL pattern into this

Route::get("/p/{lang}/{id}", function(string $lang, string $id) {
    // ...
})->name("product.view");
  1. You don’t have to update the peace of code where you generate the URLs.
  2. At some point in your code, you might be checking what is the current route and if you are on product view page, you might execute some logic. With route names it’s super easy to detect what is the route of the current request. (Will see it in later lessons).
  3. Also when you want to perform redirect to a specific route, doing this with route name is much easier.
// define a route with name "profile"
Route::get('/user/profile', function () {
    // ...
})->name('profile');

Route::get("/current-user", function() {
    // Generating Redirects...
    return redirect()->route('profile');
    // or
    return to_route('profile');
});

Discussion

Sign in to join the discussion.

No comments yet. Be the first to start the discussion!