Home » Php » php – How to set specific language for all pages in Codeigniter 4

php – How to set specific language for all pages in Codeigniter 4

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’ve translated 2 language in ‘app/Language‘ folder and set language switcher. Currently translation works fine for base url like example.com/en and example.com/sp.

My problem is when visitor visits other page like /post/cats/123 then How I set the language for all view page. What is the standard way for language setting in codeigniter 4.

Language folder –

enter image description here

language switcher code.

<div class="dropdown-menu" aria-labelledby="navbarDropdown">
    <a class="dropdown-item" href="<?= base_url('en') ?>">English</a>
    <a class="dropdown-item" href="<?= base_url('sp') ?>">Spanish</a>
</div>

Route-

$routes->get('/{locale}', 'Language::index');

Language class –

class Language extends BaseController
{

    public function index()
    {
         $locale = $this->request->getLocale();
         $this->request->setLocale($locale);
         return redirect()->back();
    }
}
How to&Answers:

I got a solution for multi language in codeigniter-4 myself that I described now. My view code is here that is clickable for selection a language –

<a class="dropdown-item" href="<?= base_url('lang/en'); ?>">English</a>
<a class="dropdown-item" href="<?= base_url('lang/es'); ?>">Español</a>

then I used a route for language-

$routes->get('/lang/{locale}', 'Language::index');

For this route I created a class Language with a method index

class Language extends BaseController
{

    public function index()
    {   $session = session();
        $locale = $this->request->getLocale();
        $session->remove('lang');
        $session->set('lang',$locale);
        $url = base_url();
        return redirect()->to($url);     
    }
}

Here I enabled session to store selected language and removed old language from session. $locale = $this->request->getLocale(); With this request I received selected language and stored into into session $session->set('lang',$locale); and redirect it to base url.

In codeigniter-4 default BaseController in initController method, I set language $language->setLocale($session->lang); for all controllers that I extends for other.

class BaseController extends Controller{
    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
      $session = \Config\Services::session();
      $language = \Config\Services::language();
      $language->setLocale($session->lang);
    }
}

Here I enabled language Library as a service $language = \Config\Services::language(); and set language with this method $language->setLocale($session->lang); using session data.