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

andrei_sharov's avatar

Laravel: change route parameters delimiter when use regex

I have Route rule:

Route::get('/cat/{category}-{brand?}', 'ListController@category')->name('category')
        ->where('category', '([0-9A-Za-z_]+)')->where('brand', '([0-9A-Za-z_]+)');

and have controller ListController and its method:

public function category(Category $category, $brand_alias = false, Request $request) {
}

When I make route url using category_alias and brand_alias everything is well, I get url like: site.com/cat/phones-apple. But when I make route url to category withous brand I get url like site.com/cat/phones-

Please advise how to remove char: - in the end of category aias when I don't use brand alias parameter.

I don't want to change delimiter to /

Thanks.

0 likes
1 reply
lostdreamer_nl's avatar

2 ways as I see:

  1. In your category method, on the first line:
$category= trim($category, '-');

To trim all - from the $brand_alias

or 2) I think the following routing would catch any last - in the route into a variable that you'd simply not use:

Route::get('/cat/{category}{separator?}{brand?}', 'ListController@category')->name('category')
        ->where('category', '([0-9A-Za-z_]+)')
        ->where('separator', '([\-]+)')
        ->where('brand', '([0-9A-Za-z_]+)');

public function category(Category $category, $separator = '-', $brand_alias = false, Request $request) {
   // simply don't use $separator here, $brand_alias and $category will never have a - at the end
}

Please or to participate in this conversation.