DEV Community

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

Posted on

11 2

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.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay