CakePHP3 routing: pass static variable to controller action

I trying to pass "language" param from CakePHP3 route, to the action, so I can set the language for those pages.

$routes->connect('/es/hola', ['controller' => 'StaticPages', 'action' => 'welcome']);
$routes->connect('/en/hello', ['controller' => 'StaticPages', 'action' => 'welcome']);

The only way i can make it wor is using a dinamyc parameter like this:

$routes->connect('/:lang/hola', ['controller' => 'StaticPages', 'action' => 'welcome'], ['pass' => ['lang']]);

But the problem is this route will be match:

/en/hola
/es/hello
...
/fr/hello

I think sould be another best way to do this in CakePHP3, but i can't found this.

Thanks!

1 answer

  • answered 2017-11-12 20:59 ndm

    If you don't want it to be dynamic, then you need to pass it in the defaults, ie alongside the controller and action:

    $routes->connect(
        '/es/hola',
        [
            'controller' => 'StaticPages',
            'action' => 'welcome',
            'lang' => 'es'
        ]
    );
    

    In the controller the parameter will be available via the request object:

    $lang = $this->request->getParam('lang'); // param('lang') before CakePHP 3.4
    

    If you want it to be passed as an argument to the controller action, you can still define it to be passed via the pass option.

    See also