Table of contents
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 :)
Read next