Laravel有一个名为 findOrfail()
的内置方法here:
未找到异常有时您可能希望在未找到模型时抛出异常 . 这在路线或控制器中特别有用 . findOrFail和firstOrFail方法将检索查询的第一个结果 . 但是,如果没有找到结果,将抛出Illuminate \ Database \ Eloquent \ ModelNotFoundException:$ model = App \ Flight :: findOrFail(1); $ model = App \ Flight :: where('legs','>',100) - > firstOrFail();
但是,如果你想编写自己的代码来处理没有找到的结果怎么办?所以在我的控制器中我想要的东西如下:
public function show($id)
{
$data = JobCardHead::where('JobCardNum', $id)->first();
If no data found then
some code
else
some code
2 回答
如果没有找到不抛出异常的方法的模型,Eloquent会返回什么?我'm guessing it' s是
null
或false
. 所以,你可以检查first()
调用的返回值:或者,知道
firstOrFail()
抛出异常,您可以将调用包装在try / catch块中:你应该选择的确切方法实际上取决于你的用例 .
UPD. 顺便说一下,如果
$id
这里是你的主键,你应该只使用find($id)
或findOrFail($id)
,as described here当没有返回记录时,Laravel会在
first()
调用时返回null
.https://github.com/laravel/framework/blob/5.2/src/Illuminate/Database/Query/Builder.php#L1548
例如,您可以将此作为更清晰的解决方案: