3

When searching for what should be a very basic and common test in Laravel, there seems to be much confusion on how to properly check weather or not a model exists and then do something with the model if it does. When searching through stackoverflow, laracasts, and the laravel documentation itself, it does not become anymore clear. If I for example run this query,

$restaurant = Restaurant::find($input["restaurant_id"]);

There are various stack overflow posts that would have me check the count(), use the exists() method which does not seem consistent, or use firstOrFail() which throws an exception. All I want to do is run a call like the one above, check if $restaurant is a valid model, and then do something if it is. There is no need for an exception in my case and I don't want to have to have to run the query again after using something like count() or exists(). The documentation has no useful information on this either which allows 4 different variable types to be returned without any mention of which case will trigger which return. Does anyone have a good handle on this topic?

Laravel checking if record exists

Eloquent ->first() if ->exists()

https://laravel.com/api/5.2/Illuminate/Database/Eloquent/Builder.html#method_find

Community
  • 1
  • 1
David B
  • 345
  • 3
  • 14

3 Answers3

7

You don't need to run any additional queries. If the record does not exist, find() will return null. You can just use a simple if to check:

if($restaurant = Restaurant::find($input["restaurant_id"]) {
    // Do stuff to $restaurant here
}
aynber
  • 22,380
  • 8
  • 50
  • 63
1

You can also use

$restaurant = Restaurant::findOrFail($input["restaurant_id"]);

Sometimes you may wish to throw an exception if a model is not found. This is particularly useful in routes or controllers. The findOrFail and firstOrFail methods will retrieve the first result of the query. However, if no result is found, a Illuminate\Database\Eloquent\ModelNotFoundException will be thrown:

From: https://laravel.com/docs/5.1/eloquent

Riyaz Shaikh
  • 90
  • 1
  • 8
  • OP states in his question "There is no need for an exception in my case", this answer will therefor not be helpful to the OP – milo526 Jul 26 '16 at 18:35
0

Its very clear in laravel docs about your question, find(),first(),get(), all return null if the model not exist,

   $model = Restaurant::find(111); // or
   $model = Restaurant::where('id',111)->first();
   if(!$model){ //if model not exist, it means the model variable is null
    }
Mohamed Akram
  • 2,244
  • 15
  • 23
  • I appreciate the answer but where is this in the docs? I cannot find it anywhere. Also in your example, where() only returns null if you use first()? – David B Jul 26 '16 at 22:43