Garry Garry - 5 months ago 8
PHP Question

What is the best way to check if an Eloquent query returns no answer?

I'm using Laravel 4. Say I have an Eloquent model (Patient) and I want to get a patient with the name Bob, I would do this:

$patient = Patient::where('name', '=', 'Bob');

What is the best way to check to see if $patient is a valid record?


If the database query does not find any matching results, it returns null. Therefore...

$patient = Patient::where('name','=','Bob')->first();

if ( is_null($patient) ) {

(Note: in your original question you forgot ->first() (or ->get()) in your query. Don't forget that or else you will get an Eloquent object instead of a result.)