【问题标题】:Laravel implicit model bindingLaravel 隐式模型绑定
【发布时间】:2020-09-22 06:33:23
【问题描述】:

在我的 Laravel 5.1 中。应用程序我使用隐式模型绑定。但是我想问一下,如果数据库中不存在被访问的资源,我该如何提供自定义响应?因此,当找不到资源时,我得到:

404 Not Found
"class": "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",

我尝试使用以下代码更改/app/Exceptions下的Handler.php中的渲染方法

    public function render($request, Exception $e)
    {
        if ($e instanceof ModelNotFoundException) {
            dd('model not found');
            //$e = new NotFoundHttpException($e->getMessage(), $e);
        }

        return parent::render($request, $e);
    }

什么都没有改变,dd 方法没有任何影响。我将代码更改为:

    public function render($request, Exception $e)
    {
        if ($e instanceof NotFoundHttpException) {
            dd('model not found');
            //$e = new NotFoundHttpException($e->getMessage(), $e);
        }

        return parent::render($request, $e);
    }

也没有任何改变。当我尝试访问的资源不存在时,我仍然收到相同的响应。

【问题讨论】:

    标签: laravel laravel-5 http-response-codes


    【解决方案1】:

    在 Laravel 5.1 中,隐式模型绑定在 RouteServiceProvider 中进行:

    $router->model('user', 'App\User'); // for binding {user} to App\User model
    

    如果您希望指定自己的“未找到”行为,请将闭包作为第三个参数传递给模型方法:

    $router->model('user', 'App\User', function () {
        dd('model not found');
    });
    

    Laravel 文档中的更多信息:https://laravel.com/docs/5.1/routing#route-model-binding

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-12
      • 2019-01-10
      • 2017-02-07
      • 2023-03-20
      • 2016-06-10
      • 2014-07-04
      • 1970-01-01
      相关资源
      最近更新 更多