title: Performing a sum() on a collection in Laravel
body: <p>I have an application with a basic forum system where users can "like" a topic multiple times. My models extend Eloquent and I'm trying to get the sum of votes a user has for a specific topic... Basically, I'm trying to accomplish something like: </p>
  
  <pre><code>$votes = Auth::user()
      -&gt;votes-&gt;has('topic_id', '=', $topic-&gt;id)
      -&gt;sum('votes');
  </code></pre>
  
  <p>However, when executing this, I get the following error...</p>
  
  <blockquote>
    <p>Call to a member function sum() on a non-object</p>
  </blockquote>
  
  <p>I've also tried</p>
  
  <pre><code>public function show($forumSlug, $topicSlug)
  {
      $topic = Topic::whereSlug($topicSlug)-&gt;first();
  
      $votes = Topic::whereHas('votes', function ($q) use ($topic)
      {
          $q-&gt;where('topic_id', '=', $topic-&gt;id)-&gt;sum('votes');
      });
  
      dd($votes);
  }
  </code></pre>
  
  <p>However, with that I receive an error stating:</p>
  
  <blockquote>
    <p>Unknown column 'ideas.id' in 'where clause' (SQL: select sum(<code>votes</code>)
    as aggregate from <code>votes</code> where <code>votes</code>.<code>idea_id</code> = <code>ideas</code>.<code>id</code> and
    <code>idea_id</code> = 1)`</p>
  </blockquote>