CakePHP 4 Custom Routing Issue with Paginator Links

Hello,

I’m working with CakePHP 4 and facing an issue with Paginator links not respecting my custom route definitions. To give you a context, I’ve set up a custom route like so:

$builder->connect(
    "/categories/{category}",
    ['controller' => 'Items', 'action' => 'category', 'items'],
    ['routeClass' => DashedRoute::class, 'pass' => ['items'],]
);

In the controller ItemsController, I have the category action defined as follows:

public function category($item_type_slug)
{
    $category_slug = $this->getRequest()->getParam('category');
    $this->loadComponent('Paginator');
    $items = $this->getItemsCatalog($item_type_slug, $category_slug);

    $this->set('items', $items['items'] ? $this->paginate($items['items']) : []);
}

I am using CakePHP’s built-in pagination for displaying items. The issue arises when accessing the second page of the items list. The Paginator generates a link that follows CakePHP’s default routing pattern (“/controller/action/param”) instead of using my custom route. Consequently, the link to the second page appears as "/items/category/items?page=2" rather than following the custom route pattern "/categories/{category}?page=2".

I’ve searched through the documentation and forums but haven’t found a clear solution to make Paginator respect my custom route in generating links. How can I adjust the Paginator or the routing setup so that the pagination links follow the custom route I’ve defined?

Any advice or pointers in the right direction would be greatly appreciated. Thank you in advance for your help!

CakePHP Version

4

PHP Version

8

Just replicated your problem and this is related to how you define your routes in your config/routes.php

You probably have something like this in your routes

$builder->connect('/categories/{action}/*', ['controller' => 'Categories']);

right?

Or maybe even this generic one

$builder->fallbacks();
// or
$builder->connect('/{controller}', ['action' => 'index']);
$builder->connect('/{controller}/{action}/*', []);

In the end I believe you are just trying to be too specific with your routes. Try

    $builder->connect(
        '/categories/{category}',
        ['controller' => 'Items', 'action' => 'category'],
        ['routeClass' => DashedRoute::class, 'pass' => ['category']]
    );

and make sure you don’t have any generic routes like I mentioned above in your controller and you should be fine.

As we discussed privately, this method unfortunately does not solve my problem.
Thank you again for your help

Problem solved !
The problem was the way I built the route, here is the great way :

$builder->connect(
    "/:category/:item",
    ['controller' => 'Categories', 'action' => 'item'],
    [
        'routeClass' => DashedRoute::class,
        'pass' => ['category', 'item'],
        'category' => '[a-z]+',
        'item' => '[a-z]+'
    ]
);