DEV Community

Cover image for Laravel 8 Eloquent Query find() and findOrFail() Example
Code And Deploy
Code And Deploy

Posted on

Laravel 8 Eloquent Query find() and findOrFail() Example

Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/laravel/laravel-8-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 both 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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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.

I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/laravel/laravel-8-eloquent-query-find-and-findorfail-example if you want to download this code.

Happy coding :)

Top comments (0)