Hello @dushyant674
I see that you have an optional parameter in the route (the slug) but that it isn't optional in the controller action.
You can change that with adding a default value, example:
public function products($slug = '')
{
dd($slug);
}
But to be honest I personal should split the route without a slug to another function then the url with a slug. And use the crud route names, see the documentation on https://laravel.com/docs/11.x/controllers#actions-handled-by-resource-controllers
The issue arises because of how optional parameters ({slug?}) are handled in Laravel routes. Let me explain the situation and clarify why the error occurs and how you can address it.
Route Definition with {slug?}
? to the route parameter makes it optional./products (without a slug) is valid and will not throw an error because the slug parameter is optional.Route::get('/products/{slug?}', [ProductsController::class, 'products'])->name('products');
Controller Method Parameter
ProductsController, the $slug parameter must have a default value if the route parameter is optional. Otherwise, Laravel will throw the "Missing required parameter" error when no slug is provided.To fix the issue, update your controller method to provide a default value for the $slug parameter:
public function products($slug = null) {
dd($slug); // Will be null if no slug is provided
}
This way:
/products/some-slug is accessed, $slug will contain the value some-slug./products is accessed, $slug will be null.{slug?}If you use {slug} (without ?), the slug parameter becomes mandatory:
Route::get('/products/{slug}', [ProductsController::class, 'products'])->name('products');
This means the route /products (without a slug) will throw a "Missing required parameter" error because Laravel expects a slug parameter in the URL.
If you need to check whether a slug was provided in the Blade view, you can use:
@if ($slug)
<p>Slug: {{ $slug }}</p>
@else
<p>No slug provided.</p>
@endif
{slug?} in your route to make the parameter optional.$slug parameter in your controller ($slug = null).$slug is null in your application logic.With these changes, everything should work correctly.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.