What is the best way to check if an Eloquent request is not responding?

I am using Laravel 4. I will say that I have an Eloquent (Patient) model and I want to get a patient named Bob, I would do this:

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

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

+15
php laravel
source share
8 answers

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

 $patient = Patient::where('name','=','Bob')->first(); if ( is_null($patient) ) { App::abort(404); } 

(Note: in the original question, you forgot ->first() (or ->get() ) in your request. Do not forget about it, otherwise you will get an Eloquent object instead of the result.)

+18
source share

use this:

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

it will return an Eulqouent model on success or throw a ModelNotFoundException after a failure.

+9
source share

I know this is old, but this was Googleโ€™s second hit on the search., For cases where you are not expecting a single entry or cannot use ->firstOrFail() (my use case is an asynchronous 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'; } 
+5
source share
 $patient = Patient::where('name','Bob')->get(); if ( $patient->isEmpty() ) { return response(['error' => 'Record not found'], 404); } 
+3
source share

Just use empty() from your native php, resolving everything, if the null object returns true, if the laravel collection from the query designer is empty (but initialized), it will also return true.

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

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

0
source share

use findOrFail($id) in case you pass id parameter to retrieve one record

As a result, I ::find($id)->firstOrFail syntax ::find($id)->firstOrFail which is completely filled with an error.

 $patient = Patient::findOrFail($id); 
0
source share

if "performance" really matters or you don't need a result model, you can use the exists method to return a boolean if there is any entry for this request:

 $isAtLeastOnePatientNamedBob = Patient::where('name', '=', 'Bob')->exists(); 
0
source share

All Articles