title: Laravel: How to get SUM of a relation column using Eloquent
body: <p><strong>How to get SUM on related model using eager loading, without loading whole relation data?</strong></p>
  
  <p>In my project there are two models, <code>Account</code> and <code>Transaction</code>. Account model <code>has many</code> transactions.</p>
  
  <p><strong>My requirement is</strong> : <strong><em>Get accounts and eager load only the sum on the related table</em></strong>.</p>
  
  <p><strong>My current code is provided</strong> : In this code <code>transactions</code> are eager loaded and sum is calculated using php. But I would prefer not to load the whole transactions. The only requirement is <code>sum('amount')</code>.</p>
  
  <p>table : <strong><em>accounts</em></strong></p>
  
  <pre><code>| id | name | address | ...
  </code></pre>
  
  <p>table : <strong><em>transactions</em></strong></p>
  
  <pre><code>| id | account_id | amount | ...
  </code></pre>
  
  <p><strong>Account.php</strong></p>
  
  <pre><code>/**
   * Get the transaction records associated with the account.
   */
  public function transactions()
  {
      return $this-&gt;hasMany('App\Models\Transaction', 'account_id');
  }
  </code></pre>
  
  <p>The following code gives each accounts and its transactions.</p>
  
  <pre><code>$account = Account::with(['transactions'])-&gt;get();
  </code></pre>
  
  <p>SUM is calculated using :</p>
  
  <pre><code>foreach ($accounts as $key =&gt; $value) {
      echo $value-&gt;transactions-&gt;sum('amount'). " &lt;br /&gt;";
  }
  </code></pre>
  
  <p>I have tried something like this, but didn't work.</p>
  
  <pre><code>public function transactions()
  {
      return $this-&gt;hasMany('App\Models\Transaction', 'account_id')-&gt;sum('amount;
  }
  </code></pre>