DEV Community

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

Posted on

Laravel 8 Eloquent updateOrCreate() Example

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

In this post, I will explain what is the usage of Laravel Eloquent updateOrCreate() and its importance. Laravel provides updateOrCreate() to help us to update the record if existing and create if doesn't. This method helps us not to manually check if the record is existing then update if not then create. See below for my example below without Laravel updateOrCreate() and with Laravel updateOrCreate().

Example without Laravel updateOrCreate()

<?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 38';
        $description = 'Description for post 38 - updated.';
        $body = 'Body for post 38.';

        $post = Post::where('title', $title)->first();

        if(is_null($post)) {
            $post = new Post([
                'title' => $title,
                'description' => $description,
                'body' => $body
            ]);
            $post->save();
        } else {
            $post->description = $description;
            $post->body = $body;
            $post->update();
        }

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

Example with Laravel updateOrCreate()

<?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::updateOrCreate([
            'title' => 'Post 3'
        ], [
            'description' => 'Description for post 3.',
            'body' => 'body for post 3 - updated.'
        ]);

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

As you can see from the above code we have the same functionality for an update or create but with the implementation of the Laravel updateOrCreate() method, we shorten our code.

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

Happy coding :)

Top comments (0)