0
votes

I have three different Http namespaces in Laravel: Frontend, Backend, and API. There is also a different namespace for each route group. Here is an example code (frontend route group) from RouteServiceProvider:

protected function mapFrontendRoutes(Router $router) {
    $router->group([
        'namespace' => 'App\Http\Controllers\Frontend',
        'middleware' => 'web',
    ], function ($router) {
        require app_path('Http/Routes/frontend.php');
    });
}

Now, I want to setup three different 404 pages for these namespaces/route groups:

  • API - show 404 response in JSON format
  • Frontend - errors/404.blade.php
  • Backend - have a separate view in backend/errors/404.blade.php

How can I create these? I have been searching the web and have come across nothing regarding this.

Laravel version: 5.2

1

1 Answers

3
votes

You can achieve that by overriding (add) renderHttpException method in App\Exceptions\Handler. The method receives the HttpException as parameter and returns a response.

Something like this:

protected function renderHttpException(HttpException $e) {

    $status = $e->getStatusCode();

    if (Request::ajax() || Request::wantsJson()) {
        return response()->json([], $status);
    } else if(Request::is('/backend/*')) { //Chane to your backend your !
        return response()->view("backend/errors.{$status}", ['exception' => $e], $status, $e->getHeaders());
    }else {
        return response()->view("errors.{$status}", ['exception' => $e], $status, $e->getHeaders());
    }

}