DEV Community

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

Posted on

 

Laravel 8 Eloquent firstOrCreate() Example

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

In this post, I will explain what is the usage of Laravel Eloquent firstOrCreate() and its importance. Laravel provides firstOrCreate() to help us to attempt to find a record in our database if not found then create a new record and return it.

Example without Laravel firstOrCreate()

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PostsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $title = 'Post 3';
        $post = Post::where('title', $title)->first();

        if (is_null($post)) {
            $post = new Post(['title' => $title]);
        }

        $post->description = 'Description for post 3.';
        $post->body = 'Body for post 3.';

        $post->save();

        print_r($post); die;
    }
}


Example with Laravel firstOrCreate()
<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PostsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $post = Post::firstOrCreate(
            ['title' => 'Post 5'],
            ['description' => 'Description for post 5.', 'body' => 'Body for post 5.']
        );

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

As you can see of the above codes have the same functionality but using the firstOrCreate() method in Laravel will shorten our code.

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

Happy coding :)

Top comments (0)

An Animated Guide to Node.js Event Loop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.