Table of contents

Laravel Eloquent Query find() and findOrFail() Example

In this post, I will share on how to use find() and findOrFail() methods in Laravel Eloquent query. And the different usage of these methods. Usually, we use find() method for finding by model primary key but sometimes we need to use abort() function helper if the primary key value is not found. That's why findOrFail() method in Laravel eloquent is useful for this kind of scenario.

 

Laravel Eloquent find() basic example

The below example will just display null if no record is found by the given ID.

$post = Post::find(1);

dd($post);

 

But if we need to abort the process if not record found using find() then see the following code below:

$post = Post::find(1);

if(is_null($post)){
   return abort(404);
}

dd($post);

 

Laravel Eloquent findOrFail() basic example

If you want to abort the process like the above code then the below code will do the same.

$post = Post::findOrFail(1);

dd($post);

 

As you can see above example using findOrFail() method will shorten your code if you need to abort the process if no record is found. But still, depend on your scenario. I hope you find this helpful.

 

Thank you for reading :)