0
0
Laravelframework~5 mins

Route parameters in Laravel

Choose your learning style9 modes available
Introduction

Route parameters let you capture parts of the URL to use in your app. This helps show different content based on the URL.

Showing a user profile page based on user ID in the URL.
Displaying a blog post using the post's slug from the URL.
Filtering products by category name in the URL.
Accessing order details using an order number in the URL.
Syntax
Laravel
Route::get('/users/{id}', function ($id) {
    return "User ID: $id";
});

Use curly braces {} to define a route parameter.

The parameter name inside braces becomes a variable in the route callback.

Examples
Captures a single parameter named 'post' from the URL.
Laravel
Route::get('/posts/{post}', function ($post) {
    return "Post: $post";
});
Captures two parameters: 'category' and 'id' from the URL.
Laravel
Route::get('/products/{category}/{id}', function ($category, $id) {
    return "Category: $category, Product ID: $id";
});
Defines an optional parameter 'id' with a default value.
Laravel
Route::get('/users/{id?}', function ($id = null) {
    return $id ? "User ID: $id" : "No user ID provided";
});
Sample Program

This route captures the 'username' from the URL and shows a welcome message using it.

Laravel
<?php

use Illuminate\Support\Facades\Route;

Route::get('/profile/{username}', function ($username) {
    return "Welcome to $username's profile!";
});
OutputSuccess
Important Notes

Route parameters are always strings from the URL.

You can make parameters optional by adding a question mark and providing a default value.

Use route model binding for automatic fetching of database records by parameter.

Summary

Route parameters let you get values from the URL to use in your app.

Define parameters with curly braces {} in your route URL.

Parameters can be required or optional.