title: How I can avoid duplicate records for insert
body: <p>I am using Laravel 5.6.29</p>
  <pre><code>if ( HarmFlag::where('post_id', '=', $postId)-&gt;where('harm_id', '=', $harm_id)-&gt;get()-&gt;isEmpty() ) {
        HarmFlag::create([
            'post_id' =&gt; $postId,
            'harm_id' =&gt; $harm_id,
            'gif_flag' =&gt; $gif_flag
        ]);
    } else {
        $harmFlag = HarmFlag::where('post_id', '=', $postId)-&gt;where('harm_id', '=', $harm_id)-&gt;first();
            $harmFlag-&gt;gif_flag = $gif_flag;
            $harmFlag-&gt;save();
       }
  </code></pre>
  <p>Now it can be seen there are duplicate records for <code>harm_id=18604</code> and <code>harm_id=18605</code>, but according to what I have coded, it should not happen.</p>
  <p><strong>Update</strong></p>
  <p>Also changed the code to</p>
  <pre><code>$harmFlag = HarmFlag::firstOrNew(['post_id' =&gt; $postId, 'harm_id' =&gt; $harm_id]);
  $harmFlag-&gt;gif_flag = $gif_flag;
  $harmFlag-&gt;save();
  </code></pre>
  <p>but still getting duplicate entries.</p>
  <p><strong>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.</strong></p>
  <p>Migration</p>
  <pre><code>Schema::create('harm_flags', function (Blueprint $table) {
      $table-&gt;increments('id');
      $table-&gt;unsignedInteger('post_id');
      $table-&gt;unsignedInteger('harm_id');
      $table-&gt;boolean('gif_flag')-&gt;default(0);
  
      $table-&gt;timestamps();
      $table-&gt;foreign('post_id')-&gt;references('post_id')-&gt;on('posts');
      $table-&gt;foreign('harm_id')-&gt;references('harm_id')-&gt;on('base_harms');
  });
  </code></pre>
  <p><strong>Update 2</strong></p>
  <p>changed to</p>
  <pre><code>HarmFlag::updateOrCreate(
            ['post_id' =&gt; $postId, 'harm_id' =&gt; $harm_id],
            [
                'gif_flag' =&gt; $gif_flag,
            ]
   );
  </code></pre>
  <p>but still getting duplicate records.</p>