Throw Down 404 Errors in Cake

Say you’re doing some simple display logic for a controller view:


function view($id=null)
{
if ($id) {
$this->set($data,$this->Model->findById($id));
} else {
return false;
}

}

In a situation like this, you always want to handle the (inevitable) situation when someone requests an invalid ID number, at which point no data would be returned in the $data variable.
Luckily, there’s a handy little function called cakeError, which lets you call a variety of Cake errors. Most of the time, you’ll want a 404 error, but it also lets you call any Cake-standard errors (you can see the full list here).
Regardless, if you want Cake to display a “404 Not Found” error message if the ID isn’t found or returns no data, do something like the following:


function view($id=null)
{
if ($id) {
$data = $this->Model->findById($id);
if (!$data) {
$this->cakeError('error404',array(array('url'=>'/')));
} else {
$this->set('data',$data);
}

} else {
return false;
}

}

That will throw up Cake’s generic 404 error page and stop further script execution for ya. If you want to have a custom 404 page, add a file named “error404.ctp” to your /app/views/error/ directory.