title: Laravel Eloquent - Merging two eloquent model results (not the collections)
body: <p>I have a table of stock movements, which shows a history of a product (receiving, moving location etc.)</p>
  
  <p>I have two queries which calculate (via aggregate sums):</p>
  
  <ol>
  <li>The original received qty.</li>
  <li>The current live qty (after things have been moved).</li>
  </ol>
  
  <p>Both of these queries return a collection of the same models. They will always have the same number of results in each, and the product_id's will always be the same. The only part that is different is the received/live qty and I want to somehow merge the individual records into a new collection. i.e.</p>
  
  <p>Single record from query 1:</p>
  
  <pre><code>0 =&gt; StockMovement {#1602 ▼
    #original: array:2 [▼
      "live_qty" =&gt; "8"
      "product_id" =&gt; "2606598e-4150-461a-9e91-10d67cce8daa"
    ]
  }
  </code></pre>
  
  <p>Single record from query 2;</p>
  
  <pre><code>0 =&gt; StockMovement {#1602 ▼
    #original: array:2 [▼
      "received_qty" =&gt; "15"
      "product_id" =&gt; "2606598e-4150-461a-9e91-10d67cce8daa"
    ]
  }
  </code></pre>
  
  <p>I am trying to end up with a merged result which looks like the following:</p>
  
  <pre><code>0 =&gt; StockMovement {#1602 ▼
    #original: array:3 [▼
      "received_qty" =&gt; "15"
      "live_qty" =&gt; "8"
      "product_id" =&gt; "2606598e-4150-461a-9e91-10d67cce8daa"
    ]
  }
  </code></pre>
  
  <p>I want to do this in a way that does not convert the Product object to an array, as I need the relationships that are embedded within it.</p>
  
  <p>Currently, I have hacked this as follows:</p>
  
  <pre><code>$live = $this-&gt;liveQtyCollection();
  $merged = $this-&gt;receivedQtyCollection()-&gt;map(function(StockMovement $received) use($live){
      $line = $live-&gt;where('product_id', $received-&gt;product_id)-&gt;first();
      return arrayToObject(array_merge($received-&gt;toArray(), $line-&gt;toArray()));
  });
  return $merged;
  </code></pre>
  
  <p>The <code>arrayToObject</code> function, recursively converts the array back into an object so I can use the arrow selector in the same way as when it was its original collection, but I am sure there must be a better way!</p>
  
  <p>I have tried:</p>
  
  <ul>
  <li>Merge</li>
  <li>Union</li>
  <li>All</li>
  </ul>
  
  <p>My end goal is to be able to use the resulting collection as follows:</p>
  
  <pre><code>@foreach($stockMovements as $stockMovement)
      {{ $stockMovement-&gt;id }}
      {{ $stockMovement-&gt;live_qty }}
      {{ $stockMovement-&gt;received_qty }}
  @endforeach
  </code></pre>