Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

MrFiliper's avatar

Route variables, add dash requre only when variant is present

Hi, I have a route definition for a product that can have multiple variants:

Route::get('/product/{code}-{variant?}/zobrazit', [App\Http\Controllers\ProductController::class, 'getShow'])->name('product.show');

I need to be "-" dash optional too, but only when the variant variable is empty. So the URLs could be like that.

/product/1 = Get product 1 with color variant 1 /product/1-1 = Get product 1 with color variant 1 /product/1-2 = Get product 1 with color variant 2

And want to do this for only one route, could it be done by one route or not?

0 likes
5 replies
s4muel's avatar
s4muel
Best Answer
Level 50

there might be some magic, but i would try making two separate routes to point to the same controller method, might work.

Route::get('/product/{code}-{variant?}/zobrazit', [App\Http\Controllers\ProductController::class, 'getShow'])->name('product.show');
Route::get('/product/{code}/zobrazit', [App\Http\Controllers\ProductController::class, 'getShow'])->name('product.show');

just put the most specific route first. and in the controller, fallback to variant = 1 if it is not set

MrFiliper's avatar

@s4muel That works, thanks! I guess there is no way to stuff it into one route?

MrFiliper's avatar

@s4muel But not working, when defining route URL.

{{ route('product.show', ['product' => $product, 'variant' => $product->variant == 1 ? null : $set->variant]) }}

s4muel's avatar

@MrFiliper oh, i see, both routes cannot have the same name, use the second without a name. should work like this

Route::get('/product/{code}-{variant?}/zobrazit', [App\Http\Controllers\ProductController::class, 'getShow'])->name('product.show');
Route::get('/product/{code}/zobrazit', [App\Http\Controllers\ProductController::class, 'getShow']);
s4muel's avatar

@MrFiliper and to the one route question... give this a try:

Route::get('/product/{code}{hyphen?}{variant?}/zobrazit', function ([App\Http\Controllers\ProductController::class, 'getShow'])
    ->where('code', "[\d]+") //at least one digit
    ->where('hyphen', "-") //exactly one hyphen (optional, as set in the route uri)
    ->where('variant', "[\d]+") //at least one digit (optional, as set in the route uri)
    ->name('product.show');

mozno pojde;)

Please or to participate in this conversation.