Laravel different 404 pages for different namespaces/route-groups

时间:2016-07-11 23:25:35

标签: php laravel

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 个答案:

答案 0 :(得分:3)

您可以通过在renderHttpException中覆盖(添加)App\Exceptions\Handler方法来实现这一目标。该方法接收HttpException作为参数并返回响应。

这样的事情:

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());
    }

}