DEV Community

Cover image for Laravel 8 Eloquent firstOr() Example
Code And Deploy
Code And Deploy

Posted on

Laravel 8 Eloquent firstOr() Example

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

In this post, I will explain what is the usage of Laravel Eloquent firstOr() and its importance. Laravel provides firstOr() that enables us to put another logic inside closure if the record is not found in our database.

I will give you several examples:

Create Not Found Record

In this example, it will search a post title record if not found then it will create a post using provided attributes then display the instance. See the below example:

$attributes = [
    'title' => 'Post 100',
    'description' => 'Description for post 100',
    'body' => 'Body for post 100'
];

$post = Post::where("title", $attributes['title'])->firstOr(function () use($attributes) {
    return Post::create($attributes);
});  

print_r($post); die;
Enter fullscreen mode Exit fullscreen mode

Display Default Not Found Record

In this example we will find the record if not found then we will display the default record.

$post = Post::where('title', 'post title'])->firstOr(function () {
    return Post::where('title', 'default post')->first();
});  

print_r($post); die;
Enter fullscreen mode Exit fullscreen mode

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

Happy coding :)

Top comments (0)