2

I just learn CodeIgniter 4 Framework. How to customize my 404 page not found?

Vickel
  • 7,879
  • 6
  • 35
  • 56
Christianto
  • 47
  • 1
  • 5

5 Answers5

6

Go to your Routes.php file and find

$routes->set404Override();

Now , If you want to display just an error message then write

    $routes->set404Override(function(){
    echo "your error message";
});

instead of

$routes->set404Override();

Or If you want to return a view then write like below:

$routes->set404Override(function(){
    return view('your_filename');
});

instead of

$routes->set404Override();
Monayem Islam
  • 294
  • 3
  • 15
1

// Would execute the show404 method of the App\Errors class

$routes->set404Override('App\Errors::show404');

// Will display a custom view

$routes->set404Override(function()
{
    echo view('my_errors/not_found.html');
});
Christianto
  • 47
  • 1
  • 5
0

To customize your 404 page, modify app/Views/errors/html/error_404.php to your liking.

ubuntux
  • 394
  • 3
  • 12
0

For custom error messages

in Config\routes.php

// Custom 404 view with error message.
$routes->set404Override(function( $message = null )
{
    $data = [
        'title' => '404 - Page not found',
        'message' => $message,
    ];
    echo view('my404/viewfile', $data);
});

in my viewfile, to display error:

<?php if (! empty($message) && $message !== '(null)') : ?>
  <?= esc($message) ?>
<?php else : ?>
  Sorry! Cannot seem to find the page you were looking for.
<?php endif ?>

from my controller:

throw new \CodeIgniter\Exceptions\PageNotFoundException('This is my custom error message');
Eeel
  • 117
  • 7
0

Expanding on @Christianto answer, in 4.3.7 at least I had to enter the full namespace path, when using a controller method to override 404.

// In Routes.php (full path)
$routes->set404Override('\App\Controllers\Start::pageNotFound');

// In the controller
public function pageNotFound() {
    return $this->view('error_404');
}
cdsaenz
  • 520
  • 1
  • 10
  • 15