title: Eloquent ORM aggregation vs MySql aggregation
body: <p>I'm working on a Laravel 5.2 project and I'm using Eloquent models, but I'm not sure how to approach to aggregation features.</p>
  
  <p>Let's say I have Product and Price models and a <code>hasMany</code> relationship, so a product can have multiple prices.</p>
  
  <p>Now, in my Product model I'd like a function that will give me an average price of the product.</p>
  
  <p>I found 2 ways to get the same result:</p>
  
  <p><strong>1.) Eloquent aggregation</strong></p>
  
  <pre><code>public function avg_price()
  {
       return $this-&gt;prices()-&gt;avg('price');
  }
  </code></pre>
  
  <p><strong>2.) MySql aggregation</strong></p>
  
  <pre><code>public function avg_price()
  {    
      return $this-&gt;prices()-&gt;groupBy('product_id')-&gt;first([\DB::raw('AVG(price) AS avg_price')])-&gt;avg_price;
  }
  </code></pre>
  
  <p>So, both of them are showing the right result, however, I'm wondering which one is better to use performance wise.</p>
  
  <p>As far as I understand, Eloquent aggregation would make a collection out of all results (prices) and then calculate the average upon it, and MySQL aggregation would simply do the AVG function in MySQL and return a single row as a result.</p>
  
  <p>I'd like to hear another opinion.
  Thanks in advance.</p>