Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can avoid duplicate records for insert

I am using Laravel 5.6.29

if ( HarmFlag::where('post_id', '=', $postId)->where('harm_id', '=', $harm_id)->get()->isEmpty() ) {
      HarmFlag::create([
          'post_id' => $postId,
          'harm_id' => $harm_id,
          'gif_flag' => $gif_flag
      ]);
  } else {
      $harmFlag = HarmFlag::where('post_id', '=', $postId)->where('harm_id', '=', $harm_id)->first();
          $harmFlag->gif_flag = $gif_flag;
          $harmFlag->save();
     }

Now it can be seen there are duplicate records for harm_id=18604 and harm_id=18605, but according to what I have coded, it should not happen.

Update

Also changed the code to

$harmFlag = HarmFlag::firstOrNew(['post_id' => $postId, 'harm_id' => $harm_id]);
$harmFlag->gif_flag = $gif_flag;
$harmFlag->save();

but still getting duplicate entries.

Interesting fact about this is for every duplicate records, the timestamp is also same. As well there is only a second record for all these situation.

Migration

Schema::create('harm_flags', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedInteger('post_id');
    $table->unsignedInteger('harm_id');
    $table->boolean('gif_flag')->default(0);

    $table->timestamps();
    $table->foreign('post_id')->references('post_id')->on('posts');
    $table->foreign('harm_id')->references('harm_id')->on('base_harms');
});

Update 2

changed to

HarmFlag::updateOrCreate(
          ['post_id' => $postId, 'harm_id' => $harm_id],
          [
              'gif_flag' => $gif_flag,
          ]
 );

but still getting duplicate records.

like image 497
Prafulla Kumar Sahu Avatar asked Dec 04 '22 18:12

Prafulla Kumar Sahu


1 Answers

You don't need to check isEmpty, you can use firstOrNew() or updateOrCreate() methods

$harmFlag = HarmFlag::firstOrNew(['post_id' => $postId, 'harm_id' => $harm_id]);
$harmFlag->gif_flag = $gif_flag;
$harmFlag->save();

or

$harmFlag = HarmFlag::updateOrCreate(['post_id' => $postId, 'harm_id' => $harm_id]);
$harmFlag->gif_flag = $gif_flag;
$harmFlag->save();

please check the document https://laravel.com/docs/5.3/eloquent#insert-update-delete

like image 105
Sethu Avatar answered Dec 06 '22 07:12

Sethu