title: Optimizing code with chunk or cursor in laravel
body: <p>I'm having <code>Company</code> Model and <code>Contact</code> Model defined in my <code>Laravel 5.4</code> application, both of them have many to many relationship. So, for example contacts model has:</p>
  
  <pre><code>public function company()
  {
      return $this
          -&gt;belongsToMany('App\Company', 'company_contact','contact_id', 'company_id')-&gt;withTimestamps();
  }
  </code></pre>
  
  <p>Now I've a data set where I want to pull all contacts data and there company details so I was using:</p>
  
  <pre><code>public function getData()
  {
      $contacts = Contact::all();
      foreach($contacts as $contact)
      {
          $getCompany = $contact-&gt;company()-&gt;withPivot('created_at')-&gt;orderBy('pivot_created_at', 'desc')-&gt;first();
          $getCompany-&gt;contacts = Company::find($getCompany-&gt;id)-&gt;contacts;
          $contact-&gt;company = $getCompany;
          $contact-&gt;companies_interested = json_decode($contact-&gt;companies_interested);
          $companies = [];
          if($contact-&gt;companies_interested)
          {
              foreach($contact-&gt;companies_interested as $companiesInterested)
              {
                  $getCompany = Company::withTrashed()-&gt;find($companiesInterested);
                  $companies[] = array(
                      'value' =&gt; $getCompany-&gt;id,
                      'label' =&gt; $getCompany-&gt;name
                  );
              }
              $contact-&gt;companies_interested = json_encode($companies);
          }
      }
      return response()-&gt;json([
          'model' =&gt; $contacts
      ], 200);
  }
  </code></pre>
  
  <p>This works perfectly fine for small data set, but while using large number of data it fails (approx 10,000 fields), I guess <code>php memory fails</code> to load when it comes to large data set. I was going through <code>Laravel</code> docs to find out the solution and came to know about <code>chunk()</code> and <code>cursor()</code> methods, Can someone guide me what can be done in this problem or what can be the approach to overcome this.</p>
  
  <p>Thanks</p>