Laravel 5.1 基于路由的自定义 404

Laravel 5.1 custom 404 based on route

我是 laravel 的新手。我想根据请求 url.

显示自定义 404 错误

示例:
网站.com/somepage

网站.com/admin/somepage

我看到了 this 的答案,但它是针对 laravel 4 的。我找不到 Laravel 5.1

的等效答案

请帮忙。谢谢!


-- 答案 --

我的代码基于 Abdul Basit

的建议
//Handle Route Not Found
if ($e instanceof NotFoundHttpException) {
    //Ajax Requests
    if ($request->ajax() || $request->wantsJson()) {
        $data = [
            'error' => true,
            'message' => 'The route is not defined',
        ];
        return Response::json($data, '404');
    } else {
        //Return view
        if (Request::is('admin/*')) {
            return Response::view('admin.errors.404', array(), 404);
        } else {
            return Response::view('errors.404', array(), 404);
        }
    }
}

//Handle HTTP Method Not Allowed
if ($e instanceof MethodNotAllowedHttpException) {
    //Ajax Requests
    if ($request->ajax() || $request->wantsJson()) {
        $data = [
            'error' => true,
            'message' => 'The http method not allowed',
        ];
        return Response::json($data, '404');
    } else {
        //Return view
        if (Request::is('admin/*')) {
            return Response::view('admin.errors.404', array(), 404);
        } else {
            return Response::view('errors.404', array(), 404);
        }
    }
}

您可以在 app\Exceptions\Handler.php

App\Exceptions\Handlerrender 方法中执行该逻辑
public function render($request, Exception $e)
{
    //Handle Route Not Found
    if ($e instanceof Symfony\Component\HttpKernel\Exception\NotFoundHttpException)
    {
        //Ajax Requests
        if($request->ajax() || $request->wantsJson())
        {
            $data = [
                'error'   => true,
                'message' => 'The route is not defined',
            ];
            return Response::json($data, '404');
        }
        else
        {
            //Return view 
            return response()->view('404');
        }
    }
    //Handle HTTP Method Not Allowed
    if ($e instanceof Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException)
    {
        //Ajax Requests
        if($request->ajax() || $request->wantsJson())
        {
            $data = [
                'error'   => true,
                'message' => 'The http method not allowed',
            ];
            return Response::json($data, '404');
        }
        else
        {
            //Return view 
            return response()->view('404'); 
        }
    }
    return parent::render($request, $e);
}

Laravel 可以轻松显示各种 HTTP 状态代码的自定义错误页面。例如,如果您希望自定义 404 HTTP 状态代码的错误页面,请创建 resources/views/errors/404.blade.php。该文件将针对您的应用程序生成的所有 404 错误提供。此目录中的视图应命名为与它们对应的 HTTP 状态代码相匹配。

检查回退路由,您可以定义一个路由,当没有其他路由匹配传入请求时将执行该路由,回退路由应始终是您的应用程序注册的最后一个路由。 https://laravel.com/docs/5.8/routing#fallback-routes

Route::fallback(function () {
    //Send to 404 or whatever here.
});