CodeIgniter Forums
How I can show 404 if locale invalid? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Discussion (https://forum.codeigniter.com/forumdisplay.php?fid=31)
+--- Thread: How I can show 404 if locale invalid? (/showthread.php?tid=74913)



How I can show 404 if locale invalid? - XTAZ - 11-24-2019

How I can show 404 if locale invalid?

My route:
$routes->add('{locale}', 'App\Controllers\Home::index');

But if I try open mysite.com/asdasdasd, or mysite.com/dad2da ... - I get HTTP code 200, I want get 404.

I must write crutch?

Then, if I write filter, how I detect what first segment used as locale, not controller?


RE: How I can show 404 if locale invalid? - mboufos - 11-25-2019

tbh i dont know about CI4 but i will save the locale on cookie and just load it Tongue


RE: How I can show 404 if locale invalid? - XTAZ - 11-25-2019

(11-24-2019, 11:58 AM)XTAZ Wrote: How I can show 404 if locale invalid?

My route:
$routes->add('{locale}', 'App\Controllers\Home::index');

But if I try open mysite.com/asdasdasd, or mysite.com/dad2da ... - I get HTTP code 200, I want get 404.

I must write crutch?

Then, if I write filter, how I detect what first segment used as locale, not controller?
I write this code:

PHP Code:
<?php namespace App\Filters;

use 
CodeIgniter\HTTP\RequestInterface;
use 
CodeIgniter\HTTP\ResponseInterface;
use 
CodeIgniter\Filters\FilterInterface;

class 
Locale implements FilterInterface
{
    public function 
before(RequestInterface $request)
    {
        
$supported_locales config('Config\\App')->supportedLocales;
        
$uri_locale $request->uri->getSegment(1);
        
        if (
in_array($uri_locale$supported_locales))
        {
            
// For pages outside of routing (404 and etc)
            
$request->setLocale($uri_locale);
        }
        
        
$use_locale $request->getLocale();
        
        if (
$uri_locale !== $use_locale)
        {
            return 
redirect()->to("/{$use_locale}/".trim($_SERVER['REQUEST_URI'], '/'));
        }
    }

    
//--------------------------------------------------------------------

    
public function after(RequestInterface $requestResponseInterface $response)
    {
        
// Do something here
    
}

If user try open site.com/awdawd, we redirects him to site.com/{defaultLocale}/awdawd and he view 404