gpt4 book ai didi

laravel - 处理Laravel中找不到的数据

转载 作者:行者123 更新时间:2023-12-03 08:27:11 24 4
gpt4 key购买 nike

Laravel有一个称为findOrfail()的内置方法,描述了here:

Not Found Exceptions

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::where('legs', '>', 100)->firstOrFail();


但是,如果您想编写自己的代码却找不到结果该怎么办?所以在我的 Controller 中,我想要类似:
public function show($id)
{
$data = JobCardHead::where('JobCardNum', $id)->first();

If no data found then
some code
else
some code

最佳答案

如果未为不引发异常的方法找到模型,那么Eloquent返回什么?我猜是nullfalse。因此,您可以检查first()调用的返回值:

$data = JobCardHead::where('JobCardNum', $id)->first();

if ($data) {
// found it
} else {
// not found
}

或者,知道 firstOrFail()引发异常,您可以将调用包装在try/catch块中:
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

您应该选择的确切方法实际上很大程度上取决于您的用例。

UPD。 顺便说一句,如果此处的 $id是此处的主键,则只需使用 find($id)findOrFail($id)as described here

关于laravel - 处理Laravel中找不到的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38264997/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com