Support the ongoing development of Laravel.io →
Eloquent Database Routing
0
moderator

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

0

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.


Explanation

  1. Route Definition with {slug?}

    • Adding a ? to the route parameter makes it optional.
    • This means the route /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');
    
  2. Controller Method Parameter

    • In your 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.

Solution

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:

  • When /products/some-slug is accessed, $slug will contain the value some-slug.
  • When /products is accessed, $slug will be null.

Why the Error Occurs Without {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.


Optional Parameter in Blade View

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

Summary

  • Use {slug?} in your route to make the parameter optional.
  • Provide a default value for the $slug parameter in your controller ($slug = null).
  • Ensure you handle cases where $slug is null in your application logic.

With these changes, everything should work correctly.

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Dushyant dushyant674 Joined 23 Dec 2024

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.