Search code examples
cakephpurl-routingcakephp-3.0

Slug route in cakephp 3


I have this route and it's OK:

Router::connect('/tour/:slug', 
     ['controller' => 'Tours','action' => 'view'],
     ['slug'=>'[^\/]+','pass'=>['slug']]
);

I want remove "/tour" , but it has Missing Controller error:

Router::connect('/:slug', 
     ['controller' => 'Tours','action' => 'view'],
     ['slug'=>'[^\/]+','pass'=>['slug']]
);

error page (in request: http://localhost/nextholiday/a_slug ): enter image description here

what should I do?


Solution

  • I'm using the same route. But it only works when the route is before:

    $routes->fallbacks(DashedRoute::class);
    

    Example (inside of Router::scope('/'...):

        $routes->connect(
            '/:slug',
            ['controller' => 'Articles', 'action' => 'view'],
            [
                'pass' => ['slug'],
                'slug' => '[^\/]+' // Taken from your example
            ]
        );
        // ...
        $routes->fallbacks(DashedRoute::class);
    

    If you are doing all right, on DebugKit Routes you will see the routes (URI template) /:controller and /:controller/:action/* just below your /:slug. All other routes must be above of /:slug.

    As mentioned, order matters. Missing Controller sometimes is shown if your Regex Pattern is wrong, on slug pattern I'm using "[a-z0-9]+(?:-[a-z0-9]+)*".