Table of contents

Laravel 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);

 

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

 

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

 

That's it I hope you found it helpful. Thank you for reading :)