Table of contents

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

 

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;

 

I hope you find this helpful. Thanks for reading :)