11

I'm using Laravel 4 framework and I've defined a whole bunch of routes, now I wonder for all the undefined urls, how to route them to 404 page?

dulan
  • 1,584
  • 6
  • 22
  • 50

5 Answers5

20

In Laravel 5.2. Do nothing just create a file name 404.blade.php in the errors folder , it will detect 404 exception automatically.

Chutipong Roobklom
  • 2,953
  • 2
  • 17
  • 20
9

Undefined routes fires the Symfony\Component\HttpKernel\Exception\NotFoundHttpException exception which you can handle in the app/start/global.php using the App::error() method like this:

/**
 * 404 Errors
 */
App::error(function(\Symfony\Component\HttpKernel\Exception\NotFoundHttpException $exception, $code)
{
   // handle the exception and show view or redirect to a diff route
    return View::make('errors.404');
});
bgallagh3r
  • 5,866
  • 1
  • 14
  • 17
  • 2
    Technically I wouldn't redirect to a route just display a 404 page when you hit a 404 route. – bgallagh3r Nov 06 '14 at 01:41
  • 1
    Yes That's what I intent to do, no redirecting, just show the 404 page, and yours is the right one, thank you! – dulan Nov 06 '14 at 01:53
6

The recommended method for handling errors can be found in the Laravel docs:

http://laravel.com/docs/4.2/errors#handling-404-errors

Use the App::missing() function in the start/global.php file in the following manner:

App::missing(function($exception)
{
    return Response::view('errors.missing', array(), 404);
});
akrist
  • 351
  • 1
  • 5
6

according to the official documentation

you can just add a file in: resources/views/errors/ called 404.blade.php with the information you want to display on a 404 error.

verax
  • 173
  • 3
  • 10
  • This documentation is for Laravel 5, but yes you're right and I've recently updated my Laravel 4.2 based project to Laravel 5. Now what if I want to have 2 404 pages, one for mobile devices and the other for desktop browsers? – dulan Nov 21 '15 at 06:43
3

I've upgraded my laravel 4 codebase to Laravel 5, for anyone who cares:

App::missing(function($exception) {...});

is NO LONGER AVAILABLE in Laravel 5, in order to return the 404 view for all non-existent routes, try put the following in app/Http/Kernel.php:

public function handle($request) {
    try {
        return parent::handle($request);
    }
    catch (Exception $e) {
        echo \View::make('frontend_pages.page_404');
        exit;
        // throw $e;
    }
}
dulan
  • 1,584
  • 6
  • 22
  • 50