Do I always have to check for $this->foo->count()
before I can $this->foo->first()
to "catch" any No query results for model [Foo].
"exceptions"?
I've tried this
public function hasValid($model)
{
try {
return $this->$model()->firstOrFail()->expiration > date('Y-m-d') ? true : false;
} catch(ModelNotFoundException $e) {
return false;
}
}
But I'm still getting No query results for model [Foo].
when the query returns an empty query set.
I don't always want to prepend any $this->foo->first()
calls with a $this->foo->count()
call just to check for this. There has to be a DRYer solution.
I've got this to be the DRYest so far:
public function hasValid($model)
{
$model = $this->$model()->first();
return isset($model) && $model->expiration > date('Y-m-d') ? true : false;
}
You need use
statement or full namespace for exception:
use Illuminate\Database\Eloquent\ModelNotFoundException;
// or:
catch(Illuminate\Database\Eloquent\ModelNotFoundException $e)
Also you can define default handler, so you can do simply this:
public function hasValid($model)
{
return ($this->$model()->firstOrFail()->expiration > date('Y-m-d')) ? true : false;
}
// in global.php or wherever, something like this:
App::error(function(Illuminate\Database\Eloquent\ModelNotFoundException $exception, $code)
{
Log::error($exception);
return Response::make('Not found', 404);
});