title: Laravel: ordering a many-many relation
body: <p>I have a many-many relation between Ingredient and Recipe, with a pivot table (ingredient_recipe).</p>
  
  <p>I'd like to get ingredients ordered by how many recipes have them. Example, if I use salt in 2 recipes and meat in 3 recipes, I'll have meat before salt.</p>
  
  <p>This is what I have. It works but it doesn't order correctly, even though the resulting query executed directly on my DB works as expected, so Laravel is doing something internally, I guess.</p>
  
  <pre><code>//Ingredient model
  public function recipesCount()
  {
      return $this-&gt;belongsToMany('Recipe')-&gt;selectRaw('count(ingredient_recipe.recipe_id) as aggregate')-&gt;orderBy('aggregate', 'desc')-&gt;groupBy('ingredient_recipe.ingredient_id');
  }
  
  public function getRecipesCountAttribute()
  {
      if ( ! array_key_exists('recipesCount', $this-&gt;relations)) $this-&gt;load('recipesCount');
  
      $related = $this-&gt;getRelation('recipesCount')-&gt;first();
  
      return ($related) ? $related-&gt;aggregate : 0;
  }
  
  //controller
  $ingredients = Ingredient::with('recipesCount')-&gt;whereHas('recipes', function($q)
                      {
                              $q-&gt;where('user_id', Auth::id());
  
                      })-&gt;take(5)-&gt;get();
  
  //outputting the last query here and executing it on my db returns correctly ordered results.
  </code></pre>
  
  <p>How can I fix it?</p>