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

screenager's avatar

URL prefix to filter certain models

I have an application with several routes:

I want to transform my web.php file in such a way, that I can call the routes like this

Where the prefix will filter the news belonging to a certain category A, B, C, ..

I don't want to define a seperate route group for every category. It should be something like Route::group(['prefix' => '{category}']

It would be handy if I can build the URL with named routes like this: route('news'), route('news', 1) . So without having to provide the prefix as a parameter. The app should read the current URL prefix to determine which prefix to use for the links.

If possible, I would also like this URL to work http://myapp.com/news/1/edit (without the prefix)

Is there any way I can easily set this up in Laravel 5.3 or Laravel 5.4 ? Or if not, are there packages out there that provide a middleware for this, and perhaps even some eloquent scopes to filter my models on the prefix?

0 likes
3 replies
SaeedPrez's avatar

@screenager perhaps something like this..

Route::pattern('category', '^cat[ABC]$');

Route::group(['prefix' => '{category?}/news'], function() {
    Route::get('/', 'NewsController@index')->name('news.index');
    Route::get('/{id}', 'NewsController@show')->name('news.show');
    Route::get('/{id}/edit', 'NewsController@edit')->name('news.edit');
});
screenager's avatar

It's also worth mentioning that when using resource controllers, you can skip the prefix from being injected into the methods signature (if your model requires this), by overwriting the callAction method in your controller :

public function callAction($method, $parameters) {
    if (isset($parameters['category'])) {
        unset($parameters['category']);
    }

    return parent::callAction($method, $parameters);
}

Please or to participate in this conversation.