Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom 404 in Laravel 4.2 with Layout

My page uses global layout and there are many views with own controllers which are using this layout. The view called from controller action like this:

class NewsController extends BaseController {

  protected $layout = 'layouts.master';

  public function index()
  {
    $news = News::getNewsAll();

    $this->layout->content = View::make('news.index', array(
        'news' => $news
    ));
  }
}

I would like to create a custom 404 page in the same way because I need the normal page layout for nested custom 404 design. Is it possible somehow? The issue is that I cannot set the HTTP status code to 404 from controller, so it's just a soft-404 yet. I know that the proper way would be send the Response::view('errors.404', array(), 404) from filter.php in App::missing() but I cannot set the layout there just the view which is not enough. Or am I wrong and it's possible somehow?

Thanks!

Update: I've created a Gist for this problem with the files what I use in the project. Maybe it helps more to understand my current state.

like image 576
Sas Sam Avatar asked Dec 01 '22 15:12

Sas Sam


2 Answers

This is my approach. Just add the following code to /app/start/global.php file

App::missing(function($exception)
{
    $layout = \View::make('layouts.error');
    $layout->content = \View::make('views.errors.404');
    return Response::make($layout, 404);
});
like image 77
manix Avatar answered Dec 04 '22 05:12

manix


You can do the trick by adding something like this on global.php and create the necessary error views.

App::error(function(Exception $exception, $code)
{
    $pathInfo = Request::getPathInfo();
    $message = $exception->getMessage() ?: 'Exception';
    Log::error("$code - $message @ $pathInfo\r\n$exception");

    if (Config::get('app.debug')) {
        return;
    }

    switch ($code)
    {
        case 403:
            return Response::view( 'error/403', compact('message'), 403);

        case 500:
            return Response::view('error/500', compact('message'), 500);

        default:
            return Response::view('error/404', compact('message'), $code);
    }
});

You can also check some laravel-starter-kit packages available around and check how they do stuffs like that. Here is my version of laravel-admin-template

like image 22
yajra Avatar answered Dec 04 '22 03:12

yajra