【发布时间】:2014-08-19 09:41:14
【问题描述】:
在$this->foo->first()“捕获”任何No query results for model [Foo].“异常”之前,我是否总是需要检查$this->foo->count()?
我试过了
public function hasValid($model)
{
try {
return $this->$model()->firstOrFail()->expiration > date('Y-m-d') ? true : false;
} catch(ModelNotFoundException $e) {
return false;
}
}
但当查询返回空查询集时,我仍然收到 No query results for model [Foo].。
我并不总是想在任何$this->foo->first() 调用之前加上$this->foo->count() 调用来检查这一点。必须有 DRYer 解决方案。
到目前为止,我认为这是最干燥的:
public function hasValid($model)
{
$model = $this->$model()->first();
return isset($model) && $model->expiration > date('Y-m-d') ? true : false;
}
【问题讨论】:
-
根据 Laravel 文档调用
->first()会返回 NULL 而不是抛出异常。您确定您使用的是->first()而不是->firstOrFail()。后者会抛出异常。
标签: php exception laravel eloquent