eloquent orm 中是否有类似 Model::findOrFail($id) 的方法?
Is there a method like Model::findOrFail($id) in eloquent orm?
Eloquent ORM 中是否有一种方法会在模型中找不到行时失败?
现在我从 table 中删除内容的方法如下所示:
public function delete($id) {
$point = Map::find($id)->first();
$point->delete();
}
但是当模型中没有 $id
时会抛出异常,我该如何根据 eloquent 进行检查?
All methods available on the query builder are also available when
querying Eloquent models.
您可以将 findOrFail()
与 Eloquent 一起使用:
$user = User::findOrFail(1);
要处理 ModelNotFoundException
只需将您的逻辑添加到 app/Exceptions/Handler.php
的 render()
方法中:
use Illuminate\Database\Eloquent\ModelNotFoundException;
class Handler extends ExceptionHandler
{
public function render($request, Exception $e)
{
if ($e instanceof ModelNotFoundException) {
abort(404);
}
}
}
Eloquent ORM 中是否有一种方法会在模型中找不到行时失败? 现在我从 table 中删除内容的方法如下所示:
public function delete($id) {
$point = Map::find($id)->first();
$point->delete();
}
但是当模型中没有 $id
时会抛出异常,我该如何根据 eloquent 进行检查?
All methods available on the query builder are also available when querying Eloquent models.
您可以将 findOrFail()
与 Eloquent 一起使用:
$user = User::findOrFail(1);
要处理 ModelNotFoundException
只需将您的逻辑添加到 app/Exceptions/Handler.php
的 render()
方法中:
use Illuminate\Database\Eloquent\ModelNotFoundException;
class Handler extends ExceptionHandler
{
public function render($request, Exception $e)
{
if ($e instanceof ModelNotFoundException) {
abort(404);
}
}
}