Laravel: How to respond with custom 404 error depending on route

bulicmatko picture bulicmatko · Jul 31, 2013 · Viewed 9.4k times · Source

I'm using Laravel4 framework and I came across this problem.

I want to display a custom 404 error depending on requested url.

For example:

Route::get('site/{something}', function($something){
    return View::make('site/error/404');
});

and

Route::get('admin/{something}', function($something){
    return View::make('admin/error/404');
});

The value of '$something' is not important.

Shown example only works with one segment, i.e. 'site/foo' or 'admin/foo'. If someone request 'site/foo/bar' or 'admin/foo/bar' laravel will throw default 404 error.

App::missing(function($exception){
    return '404: Page Not Found';
});

I tried to find something in Laravel4 documentation but nothing is just right for me. Please help :)

Thank you!

Answer

user1669496 picture user1669496 · Jul 31, 2013

In app/start/global.php

App::missing(function($exception) 
{
    if (Request::is('admin/*'))
    {
        return Response::view('admin.missing',array(),404);
    }
    else if (Request::is('site/*'))
    {
        return Response::view('site.missing',array(),404);
    }
    else
    {
         return Response::view('default.missing',array(),404);
    }
});

In your view, you can find $something with {{ Request::path(); }} or {{ Request::segment(); }}