Laravel updateOrCreate Model
The code that you need is "updateOrCreate()" method and this code will first try to update the model if it does already exist and otherwise it will create a new modal.
<?php use App\Models\Post; Post::updateOrCreate( ['slug' => 'hello'], ['title' => 'Hello World', 'slug' => 'hello', 'created_at' => now()] );
Laravel udpateOrInsert using Fluent (DB Facade)
You can also make use of the "updateOrInsert()" method and this is available for the DB facade. This method works exactly the same as "updateOrCreate" and you can refer the code below for the full implementation.
<?php use Illuminate\Support\Facades\DB; DB::table('posts')->updateOrCreate( ['slug' => 'hello'], ['title' => 'Hello World', 'slug' => 'hello', 'created_at' => now()] );
Leave a reply