title: Laravel - Calling my Web services Api multiple times bypass the logic of single entry in database and duplication record in database
body: <p>I've a web services Api 
  Api inserts data multiple times in database while it has only to <strong>insert only one time</strong> and <strong>update second time</strong> If record exist.</p>
  
  <p>The Problem occurring due to Transaction. I've brief all thing what's happening here.</p>
  
  <p>Laravel 5.4
  Database: Maria Db 10.1.21
  Host: Localhost</p>
  
  <p>web service Includes </p>
  
  <ul>
  <li>call external apis to fetch result </li>
  <li>store fetch result in database</li>
  </ul>
  
  <p>// code here</p>
  
  <pre><code>   public function getWebsiteDetails(Request $request) {
      Log::info("call ");
      try 
      {
       return DB::transaction(function () use($request)  
      {
  
      //  Get record from website_master of given business id
      $businessWebsiteRecord = Website::where([
          'business_id' =&gt; $businessId
      ])-&gt;first();
  
      // calling external api to get result
      $pageSpeedResult = $this-&gt;pageSpeedResult($url);
  
      Log::info("crossed external api point");
  
      /**
       * Again check to confirm record is exist or not
       * code write to only for testing purpose
       */
      $recordChecker = Website::where
      (
          'business_id', $businessId
      )-&gt;first();
  
      if(!empty($recordChecker))
      {
      Log::info("if" );
      }
      else
      {
      Log::info("else");
      }
  
      /**
      * Update record if exist
      * else
      * Create record
      */
      Website::updateOrCreate(
      ['business_id' =&gt; $businessId],
      [
      'website' =&gt; $url
      ]
      );
  
      // saving data in another table after some operatins
      $thirdObj-&gt;globalIssueGenerator(/* some data*/);
  
      return $this-&gt;helpReturn('Website data saved &amp; issues are generated in system');
      });
  
      } catch (Exception $e) {
      Log::info(" getWebsiteDetails &gt;&gt; " . $e-&gt;getMessage());
      return $this-&gt;helpError(1, 'Some Problem happened to run script.');
      }
      }
  </code></pre>
  
  <p>I've to add only single row entry in database table. But the problem is 
  If I <strong>call api multiple times</strong> it <strong>inserts data multiple times</strong> in database <strong>while it has only to add first/single time</strong>. 
  As Laravel <code>Updateorcreate</code> function is using. </p>
  
  <p><strong>Test Case</strong></p>
  
  <p>If I call APi first time and then again hit that api <strong>second time after 3-5</strong> seconds </p>
  
  <p>That api will bypass the check and re-insert data like insert data in multiple times like shown in this screenshot. </p>
  
  <p><a href="https://i.stack.imgur.com/aOB9x.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aOB9x.jpg" alt="enter image description here"></a></p>
  
  <p>That's why I using below code to check.</p>
  
  <pre><code>/**
  * Again check to confirm record is exist or not
  * code write to only for testing purpose
  */
  
  $recordChecker = Website::where
  ('business_id', $businessId)-&gt;first();
  
  if(!empty($recordChecker))
  {
  Log::info("if");
  }
  else
  {
  Log::info("else");
  }
  </code></pre>
  
  <p><strong>Logs:</strong></p>
  
  <p>so logs generated time same like in database insertion screenshot.</p>
  
  <pre><code>[2018-02-12 06:18:58] local.INFO: call   
  [2018-02-12 06:19:03] local.INFO: call   
  [2018-02-12 06:19:16] local.INFO: crossed external api point
  </code></pre>
  
  <p><strong>Going in else because data not available in database</strong></p>
  
  <pre><code>[2018-02-12 06:19:16] local.INFO: else
  </code></pre>
  
  <p><strong>like in screenshot data has been inserted in database.</strong></p>
  
  <p><strong>Second Call logs</strong></p>
  
  <pre><code>[2018-02-12 06:19:19] local.INFO: else
  [2018-02-12 06:19:19] local.INFO: crossed external api point
  </code></pre>
  
  <p><strong>Again Going in else because data has not been in database yet.</strong></p>
  
  <h2>Data has been submitted in database but yet second call response is on the way</h2>
  
  <h2><strong>Problem Detected:</strong></h2>
  
  <p><strong>I'm using Transaction</strong> 
  I'm updating two tables by inserting/updating a record. </p>
  
  <p><strong>Without Transaction</strong>
  If I comment transaction code and apply above mentioned test cases data insert only single time. What I require.</p>
  
  <p>Here's the logs of without transaction</p>
  
  <pre><code>[2018-02-12 06:59:56] local.INFO: call   
  [2018-02-12 07:00:00] local.INFO: call   
  [2018-02-12 07:00:14] local.INFO: crossed external api point  
  </code></pre>
  
  <p><strong>Going in else because data not available in database so data will be create</strong></p>
  
  <pre><code>[2018-02-12 07:00:14] local.INFO: else  
  
  [2018-02-12 07:00:17] local.INFO: crossed external api point  
  </code></pre>
  
  <p>Going in if because data available in database</p>
  
  <pre><code>[2018-02-12 07:00:17] local.INFO: if  
  </code></pre>
  
  <p>But I can't remove transaction because after inserting data in first table most operation done and insert multiple data in table.</p>
  
  <p>I'm thinking to use different action to handle to update flag in file system or in Redis but that's a different technique whichI'll handle this.</p>
  
  <p>I want if any one has fix of this because I've more web services which I'm using same technique</p>
  
  <p>FUll Code</p>
  
  <pre><code>public function getWebsiteDetails(Request $request)
      {
          Log::info("call ");
          try {
              return DB::transaction(function () use($request)
              {
                  $thirdObj = new ThirdPartyEntity();
  
                  // user extract
                  $checkPoint = $this-&gt;setCurrentUser($request-&gt;get('token'))-&gt;userAllow();
  
                  $user = $checkPoint['records'];
                  $businessDetail = $this-&gt;businessEntity-&gt;userSelectedBusiness($user);
  
                  $businessDetail = $businessDetail['records'];
  
                  $userId = $user['id'];
                  $businessId = $businessDetail['business_id'];
                  $url = $businessDetail['website'];
  
                  /**
                   * Get record from website_master of given business id
                   */
                  $businessWebsiteRecord = Website::where([
                      'business_id' =&gt; $businessId
                  ])-&gt;first();
  
                  // if business_master (url) is exist then go to if block
                  if ($url != '') {
                      $data = [];
  
                          $pageSpeedScore = '';
                          $mobileReadyScore = '';
                          $data['website'] = $url;
  
                          $url = 'http://'.$url;
                          $pageSpeedResult = $this-&gt;pageSpeedResult($url);
  
  
                          if( $pageSpeedResult['_metadata']['outcomeCode'] == 200 )
                          {
                              $pageSpeedData = $pageSpeedResult['records'];
  
                              $speedResult = json_encode($pageSpeedData['formattedResults']['ruleResults']);
  
                              $data['title_tag'] = $pageSpeedData['title'];
                              $data['page_speed_score'] = $pageSpeedData['score'];
                              $data['page_speed_suggestion'] = $speedResult;
  
                              $pageSpeedScore = $pageSpeedData['score'];
                          }
                          else
                          {
                              $speedResult = NULL;
  
                              $data['title_tag'] = NULL;
                              $data['page_speed_score'] = NULL;
                              $data['page_speed_suggestion'] = NULL;
                          }
  
                      $mobileFriendlyResult = NULL;
  
                      $data['mobile_ready_score'] = 0;
                      $data['mobile_ready'] = 0;
                      $data['mobile_ready_suggestion'] = NULL;
  
                      $data['google_analytics'] = 0;
  
                          Log::info("busnes " . $businessId);
                          Website::updateOrCreate(
                              ['business_id' =&gt; $businessId],
                              $data
                          );
  
                      $issueData = []
                          $thirdObj-&gt;globalIssueGenerator($userId, $businessId, '', $issueData, 'website', 'website');
  
  
                      return $this-&gt;helpReturn('Website data saved &amp; issues are generated in system');
                  }
              });
  
          } catch (Exception $e) {
              Log::info(" getWebsiteDetails &gt;&gt; " . $e-&gt;getMessage());
              return $this-&gt;helpError(1, 'Some Problem happened to run script.');
          }
      }
  </code></pre>