Search code examples
phpcodeignitercodeigniter-4

How to throw show_404 if file not exist in Codeigniter 4



I'm using Codeigniter 4 for my application.
If the view php page file is missing in Codeigniter 3, I use these codes to throw a 404 error.

public function family($type)
{
    $page = 'family';
    if (!file_exists(APPPATH.'views/pages/family/'.$page.'.php')) show_404();
    $data = array(
        'title'   => 'Families',
        'content' => 'family/'.$page
    );
    return view('index', $data);
}

Using Codeigniter 4 I'm trying to use the same, but it doesn't redirect to 404. enter image description here


Solution

  • public function family($page)
    {
        $filepath = WRITEPATH . 'uploads/' . $page;
    
        if (!file_exists($filepath)) {
            return $this->controller->throwPageNotFoundException();
        }
    
        $data = array(
            'title'   => 'Families',
            'content' => 'family/'.$page
        );
        return view('index', $data);
    }