Home » Laravel firstOrCreate: Eloquent Operations Makes Super Easy

Laravel firstOrCreate: Eloquent Operations Makes Super Easy

Loved it? Please Share on Social Media

Introduction:

Hey, What’s up, everybody? I hope you are doing fine; today, we will discuss the laravel firstOrCreate function. Laravel’s firstOrCreate function inserts database column row data on a condition basis.
Sounds confusing?? Please follow the steps below and do them on your end for maximum learning output from this post.

First Glance of Laravel firstOrCreate Function:

Please look at the code below. It is a basic structure of a firstOrCreate function. Now, the laravel firstOrCreate function has two parameters.

The first parameter accepts an array for checking the database row’s existence, and the second takes an array for value pairs. The Laravel firstOrCreate function will use value pairs when the first attributes return false, but only in that case.

<?php

use App\Models\Post;
 
$post = Post::firstOrCreate([
    'name' => 'How to use firstOrCreate function'
]);

As you can see, we are trying to insert a post name into the database table. Now, when the laravel firstorcreate function finds your post name in the database table, it will not insert it. But if the name is absent, it will insert the new data.

Create a Post without the Laravel firstOrCreate Function

Now, see the second code snippet. This snippet will clarify why you need the laravel firstorcreate function instead of doing this manually. Now, see the code snippet below to understand how our code can repeat so many times.

<?php
   
namespace App\Http\Controllers;
  
use App\Models\Post;
use Illuminate\Http\Request;
  
class PostController extends Controller
{
    public function store(Request $request)
    {
        $post = Post::where('name', $request->name)->first();
  
        if ($post) {
            $post= new Post(['name' => $name]);
        }
  
        $post->slug = 'CREATED NEW How to use firstOrCreate function';
        $post->body = 'post body of how to use firstOrCreate function.';
  
        $post->save();
        print_r($post);
    }
}

Create a Post Using the laravel firstOrCreate Function

Now, look at the updated code snippet below. In this case, we are using this function. It’s a lot cleaner code to look at. Now, we don’t have any redundant codes anymore.

<?php
  
namespace App\Http\Controllers;
  
use App\Models\Product;
use Illuminate\Http\Request;
  
class PostController extends Controller
{
    public function store()
    {
       $post= Post::firstOrCreate([
    	    ['name' => 'How to use firstOrCreate function'],
            [
                 $post->slug = 'CREATED NEW How to use firstOrCreate function', 		     
                 $post->body = 'post body of how to use firstOrCreate function.'
            ]
        );
  
        print_r($post);
    }
}

From the upper code snippet, we notice that by using the this function, you can prevent our redundant code easily instead of manually doing this. You can check their documentation for more.

Test The Application

At last, we will start our local server using our artisan command. php artisan serve If there is no problem, our code will work fine, and the project will be running now at http://127.0.0.1:8000/ or http://locahost:8000/.

Conclusion:

Finished! That’s all about our tutorial. Although this tutorial cannot make you an expert in this function, it will give you some fundamental knowledge of how to work with this kind of thing in the future. Thank you so much for reading the whole tutorial from the beginning. If this tutorial helps you a little bit, then remember to share this post on social media. If you have questions, suggestions, or tips regarding this post, let us know via our Contact Us page.


Loved it? Please Share on Social Media

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.