处理Laravel中找不到的数据 [英] Dealing with data not found in Laravel
问题描述
Laravel有一个称为findOrfail()
的内置方法,在此处:
Laravel has a built-in method called findOrfail()
described here:
未发现异常
Not Found Exceptions
有时候,如果找不到模型,您可能希望抛出异常.这在路由或控制器中特别有用. findOrFail和firstOrFail方法将检索查询的第一个结果.但是,如果未找到结果,将抛出Illuminate \ Database \ Eloquent \ ModelNotFoundException:
Sometimes you may wish to throw an exception if a model is not found. This is particularly useful in routes or controllers. The findOrFail and firstOrFail methods will retrieve the first result of the query. However, if no result is found, a Illuminate\Database\Eloquent\ModelNotFoundException will be thrown:
$ model = App \ Flight :: findOrFail(1);
$model = App\Flight::findOrFail(1);
$ model = App \ Flight :: where('legs','>',100)-> firstOrFail();
$model = App\Flight::where('legs', '>', 100)->firstOrFail();
但是,如果您想编写自己的代码,但未找到结果,该怎么办?所以在我的控制器中,我想要类似的东西:
But what if you want to write your own code which deals with no result found. So in my controller I want something like:
public function show($id)
{
$data = JobCardHead::where('JobCardNum', $id)->first();
If no data found then
some code
else
some code
推荐答案
如果未为不引发异常的方法找到模型,那么雄辩地返回什么?我猜是null
或false
.因此,您可以检查first()
调用的返回值:
What does Eloquent return in case no model is found for the methods that do not throw an exception? I'm guessing it's either null
or false
. So, you could check the return value of the first()
call:
$data = JobCardHead::where('JobCardNum', $id)->first();
if ($data) {
// found it
} else {
// not found
}
或者,知道firstOrFail()
会引发异常,您可以将调用包装在try/catch块中:
Or, knowing that firstOrFail()
throws an exception, you could wrap the call in a try/catch block:
use Illuminate\Database\Eloquent\ModelNotFoundException;
//..
try {
$data = JobCardHead::where('JobCardNum', $id)->first();
} catch (ModelNotFoundException $e) {
// Data not found. Here, you should make sure that the absence of $data won't break anything
}
// Here $data is an instance of the model you wanted
您应该选择的确切方法实际上取决于您的用例.
The exact approach you should pick actually depends on your usecase a lot.
UPD.顺便说一句,如果$id
这是这里的主键,则您只需使用find($id)
或findOrFail($id)
,
UPD. By the way, if $id
here is your primary key here, you should simply use find($id)
or findOrFail($id)
, as described here
这篇关于处理Laravel中找不到的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!