Do I always need to call & # 8594; count () to & # 8594; first () to prevent "No query results for model [Foo]"?

Do I always need to check $this->foo->count()

so I can $this->foo->first()

"catch" any No query results for model [Foo].

"exceptions"?

I 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 still get No query results for model [Foo].

when the query returns an empty queryset.

I do not always want to add any call $this->foo->first()

with a call $this->foo->count()

to check it out. There must be a DRYer solution.

I have DRYest so far:

public function hasValid($model)
{   
        $model = $this->$model()->first();
        return isset($model) && $model->expiration > date('Y-m-d') ? true : false;
}

      

+3


source to share


1 answer


An exclusion requires an expression use

or full namespace:

use Illuminate\Database\Eloquent\ModelNotFoundException;

// or:

catch(Illuminate\Database\Eloquent\ModelNotFoundException $e)

      



You can also define a default handler, so you can do it simply:

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);
});

      

+1


source







All Articles