ModelNotFoundException

ModelNotFoundException

本文介绍了如何在Laravel雄辩的模型中重写ModelNotFoundException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有可能在某些条件/查询中找不到Laravel的Eloquent模型时抛出自定义异常?

I'm wondering, if it's possible, to throw custom exception, when on some condition/query Laravel's Eloquent model is not found?

例如,如果我有一个Page模型,如何抛出自定义的PageNotFound异常?

For example, if I have a Page model, how can I throw my custom, PageNotFound exception?

<?php 

namespace App;

use Illuminate\Database\Eloquent\Model;

class Page extends Model {
}

此模型将使用给定消息抛出ModelNotFoundException:

This model will throw ModelNotFoundException with the given message:

No query results for model [App\Page].

推荐答案

app/Exceptions/Handler.php中,尝试将以下代码添加到呈现函数的顶部

In app/Exceptions/Handler.php try adding the following code to the top of the render function

  public function render($request, Exception $e)
        {
            if ($e
                instanceof
                \Illuminate\Database\Eloquent\ModelNotFoundException) 
            {
              abort(404);
            }

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

编辑
一旦捕获到ModelNotFoundException对象,就可以对其调用 getModel() 以获取模型的类名.

EDIT
Once you catch the ModelNotFoundException object, you can call getModel() on it to get the classname of the model.

这篇关于如何在Laravel雄辩的模型中重写ModelNotFoundException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 08:16