How to define a route with a default value for a parameter in Laravel?

To define a route with a default value for a parameter in Laravel, you can use the optional method provided by Laravel's route facade. Here's an example of how to do it:

use Illuminate\Support\Facades\Route; Route::get('user/{name?}', function ($name = 'John Doe') { return "Welcome, $name!"; })->name('user.profile');

In the above example, we have defined a route with the parameter {name?}. The ? after the parameter makes it optional. In the anonymous function, we have set the default value for the $name parameter to be 'John Doe'. So if the name parameter is not provided in the URL, it will default to 'John Doe'.

You can also assign a name to the route using the name method, as shown in the example. This will allow you to generate URLs for the route using the route name and passing the optional parameter if needed.

$url = route('user.profile', ['name' => 'Jane Smith']);

In the above example, the $url variable will hold the generated URL for the route with the provided name parameter. If the name parameter is not provided, the default value 'John Doe' will be used.