DEV Community

Cover image for Laravel 8 Eloquent Query first() and firstOrFail() Example
Code And Deploy
Code And Deploy

Posted on

Laravel 8 Eloquent Query first() and firstOrFail() Example

Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/laravel/laravel-8-eloquent-query-first-and-firstorfail-example

In this Laravel example, I'm sharing the first() and firstOrFail() methods on the Laravel Eloquent query. The Laravel Eloquent first() method will help us to return the first record found from the database while the Laravel Eloquent firstOrFail() will abort if no record is found in your query.

So if you need to abort the process if no record is found you need the firstOrFail() method on Laravel Eloquent.

Below is an example of each.

Laravel Eloquent first() basic example

The below example will display null if no record is found.

$post = Post::where('title', 'Post 1')->first();

dd($post);
Enter fullscreen mode Exit fullscreen mode

But if you need to abort using first() method then this is the example code:

$post = Post::where('title', 'Post 111')->first();

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

Enter fullscreen mode Exit fullscreen mode

As you can see we added checking if the returned is null. Then call abort() function.

Laravel Eloquent firstOrFail() basic example

But using the code example below our code will be shortened if you need to abort the process if no record is found using firstOrFail() method in Laravel eloquent.

$post = Post::where('title', 'Post 1')->firstOrFail();

dd($post);
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)