Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 563
Garry Pettet Avatar asked Apr 10 '14 16:04

Garry Pettet


People also ask

How do you check if not null with eloquent?

Check if not null: whereNotNullSELECT * FROM users WHERE last_name IS NOT NULL; The equivalent to the IS NOT NULL condition in Laravel Eloquent is the whereNotNull method, which allows you to verify if a specific column's value is not NULL .

How check query result is empty in PHP?

PHP empty() Function The empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true. The following values evaluates to empty: 0.

How do you find an eloquent query?

If you write your query in Tinkerwell anyway, you can highlight the Eloquent query and press Cmd+Shift+R (or Ctrl+Shift+R if you are on Windows) and Tinkerwell profiles the query directly in the editor. You see all executed queries, the time that the query run, the memory consumption and even the peak for your memory.


2 Answers

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

like image 194
Jake Wilson Avatar answered Sep 18 '22 21:09

Jake Wilson


use this:

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

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

like image 45
Jarek Tkaczyk Avatar answered Sep 20 '22 21:09

Jarek Tkaczyk