Laravel:失败时处理findOrFail()

问题描述 投票:7回答:5

我正在寻找类似于findOrDo()的东西。找不到数据时,请执行此操作。可能像

Model::findOrDo($id,function(){
   return "Data not found";
});

laravel中是否有任何类似的东西可以让我优雅而精美地做到这一点?

*我尝试使用谷歌搜索,但找不到一个

php laravel laravel-5.1
5个回答
12
投票
use Illuminate\Database\Eloquent\ModelNotFoundException;

// Will return a ModelNotFoundException if no user with that id
try
{
    $user = User::findOrFail($id);
}
// catch(Exception $e) catch any exception
catch(ModelNotFoundException $e)
{
    dd(get_class_methods($e)) // lists all available methods for exception object
    dd($e)
}

4
投票

另一个选择是修改默认的Laravel异常处理程序,该代码在app / Exceptions / Handler.php中的render()函数上进行了更改:

public function render($request, Exception $e)
{
    if(get_class($e) == "Illuminate\Database\Eloquent\ModelNotFoundException") {
        return (new Response('Model not found', 400));
    }
    return parent::render($request, $e);
}

以这种方式而不是得到500,而是通过自定义消息发回400,而不必对每个findOrFail()都进行尝试捕获>


2
投票

替代方法可以是评估一个集合。因此,


0
投票

默认情况下,当您在Laravel 5应用程序中使用Eloquent模型的findOrFail并失败时,它将返回以下错误:


0
投票

从Laravel v5.7开始,您可以执行此操作(retrieving single model答案的@thewizardguy变体)

© www.soinside.com 2019 - 2024. All rights reserved.