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?
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
@s4muel That works, thanks! I guess there is no way to stuff it into one route?
@s4muel But not working, when defining route URL.
{{ route('product.show', ['product' => $product, 'variant' => $product->variant == 1 ? null : $set->variant]) }}
@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']);
@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 sign in or create an account to participate in this conversation.