Table of contents
In this post, I will explain what is the usage of Laravel 8, and 9 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;
}
}
Â
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;
}
}
Â
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.
Â
That's it. I hope it helps. Thank you for reading :)
Read next