title: Laravel using filter and map instead of foreach
body: <p>I have two models, <code>Plan</code> and <code>Transactions</code>. Each <code>Plan</code> can have many <code>Transactions</code>. I want to get the total amount of all transactions related to all plans. Right now I am doing it like this:</p>
  
  <pre><code>    $plans = $this-&gt;plan-&gt;with('transactions')-&gt;get();
  
      $total = [];
  
      foreach($plans as $plan)
      {
          foreach($plan-&gt;transactions as $transaction)
          {
              $total[] = $transaction-&gt;amount;
          }
      }
  
      dd(array_sum($total)); // Works, I get the total amount of all transactions that are related to a Plan.
  </code></pre>
  
  <p>But I want to get rid of the foreach loops and use <code>filter</code> and/or <code>map</code> instead. I have tried the following:</p>
  
  <pre><code>    $test = $plans-&gt;filter(function ($plan) {
          return $plan-&gt;has('transactions');
      })-&gt;map(function ($plan) {
          return $plan-&gt;transactions;
      })-&gt;map(function ($transaction) {
          return $transaction; // Not sure what to do here, $transaction-&gt;amount doesn't work
      });
  </code></pre>
  
  <p>I'm sorta getting stuck in this last bit, where I end up with a collection of collections. Any ideas of how to accomplish this, at least without using the foreach loops? Perhaps maybe in the query itself?</p>
  
  <p>So what I have is a few <code>Plans</code>, and each <code>Plan</code> can have many <code>Transactions</code>. Each <code>Transaction</code> has an <code>amount</code> field, in which I store the amount for each <code>Transaction</code>. I want to get the TOTAL AMOUNT for ALL transactions which are related to a Plan. So, the sum of the transactions.amount.</p>