ModelNotFoundException

ModelNotFoundException

本文介绍了Laravel:在失败时处理findOrFail()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am looking for something which can be like findOrDo(). Like do this when data not found. Something could be like

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

laravel中有类似的东西可以使我优雅而精美地完成吗?

Is there any similar thing in laravel that I can do this elegantly and beautifully ?

*我试过谷歌搜索,但找不到

*I tried googling but could not find one

推荐答案

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

这篇关于Laravel:在失败时处理findOrFail()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 04:40