简体   繁体   中英

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) ) {
  App::abort(404);
}

(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.)

use this:

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

it will return Eulqouent model on success or throw ModelNotFoundException upon failure.

I know this is old, but this came up as the 2nd google hit on a search, so . . . for cases where you are not expecting one record or cannot use ->firstOrFail() (my use case is an async typeahead api that returns up to 10 results) the only thing that worked for me was count():

$patient = Patient::where('name', '=', 'Bob')->get(); //you could have more than one bob
if (!count($patient)) {
    return 'No records found';
}
$patient = Patient::where('name','Bob')->get();

if ( $patient->isEmpty() ) {
  return response(['error' => 'Record not found'], 404);
}

Something like Patient::where('name', '=', 'Bob')->exists() may work. It will return a boolean.

Just use empty() from native php will solve everything, if object null it will return true, if laravel's collection from query builder is empty (but initialized) it will return true too.

$contributor = Contributor::whereVendor('web')->first();
if(empty($contributor)){
   ...
}

use findOrFail($id) in case of you are passing id parameter to fetch a single record

I ended up on this while seeking solution of ::find($id)->firstOrFail syntax which is error-full.

$patient = Patient::findOrFail($id);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM