Tuesday, February 15, 2022

[FIXED] CakePHP 3.x optional language routing

Issue

I'm creating a multi language site. I want it to be in english when no language parameter is set and a different language when a language parameter is set.

My routing looks as follows:

$routes->connect('/:language/:controller/:action/*');

The issue is as follows:

When I visit www.mydomain.com/users/login it works fine.

When I visit www.mydomain.com/fr/users/login it works fine (in french).

But when I visit www.mydomain.com/users/login/1 where the 1 is a custom named parameter I want to parse, it naturally thinks that users is the language and login is my controller and 1 is my action.

I'm aware that if I force there to always be a language parameter this would no longer be an issue but I don't want the english version to be at www.mydomain.com/en/. I want it to be at www.mydomain.com.

Is this achievable? Is there a way to ignore the language parameter if it's not fr or es etc?


Solution

You can specify a regular expression for matching route elements. So you need something similar to

$routes->connect(
    '/:language/:controller/:action/*', 
    [], 
    ['language' => 'fr|es']
);

Consult the CakePHP manual / API for more details.



Answered By - ADmad

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.