mardi 14 août 2018

Best way to check if model returns results in laravel

I'm fairly new to laravel and looking for the best method for checking whether a model has returned any results or not.

The example below will return null if not results are found. Which is perfect if you only ever want the first result.

$results = FooBar::where(['col' => 'someVal', 'col3' => 'value'])->first();

The example below will return an object regardless of there being any results.

$results = FooBar::where(['col' => 'someVal', 'col3' => 'value'])->get();

Therefore i'm currently having to do this every time:

if($results && count($results)) {
     // then do stuff
}

I have methods that call various models and the code looks ugly and inefficient with all of these count() functions.

FYI I'm currently using laravel 5.1 due to our php version (not within my control).



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire