title: Using COUNT() function in Eloquent ORM (outside Laravel)
body: <p>I'm trying to replicate an SQL query with Eloquent ORM:</p>
  
  <pre><code>SELECT DISTINCT name, COUNT(name) AS total
  FROM tags
  WHERE question_id IS NOT NULL
  GROUP BY name
  ORDER BY name ASC;
  </code></pre>
  
  <p>Here is my attempt in Eloquent ORM:</p>
  
  <pre><code>$query = Tag::query();
  $query-&gt;orderBy('name', 'asc');
      -&gt;groupBy('name');
      -&gt;select( array('count(name) as total') );
      -&gt;whereNotNull('question_id');
  </code></pre>
  
  <p>However, this gives me the following error: </p>
  
  <blockquote>
    <p><code>SQLSTATE[42S22]: Column not found: 1054 Unknown column 'count(name)' in 'field list' (SQL: SELECT</code>COUNT(name)<code>AS</code>total<code>FROM</code>tags<code>WHERE</code>tags<code>.</code>deleted_at<code>IS NULL AND</code>question_id<code>IS NOT NULL GROUP BY</code>name<code>ORDER BY</code>name<code>ASC)</code></p>
  </blockquote>
  
  <p>... so clearly I'm not using it properly.</p>
  
  <p>I found a post saying that I should use <code>DB::raw('COUNT(name) as total')</code> but I don't know where DB class is as I'm not working within Laravel. If I need to use this, how can I use it outside Laravel. I tried <code>use</code> for both:</p>
  
  <pre><code>use Illuminate\Database\Connection as DB;
  use Illuminate\Database\Query\Builder as DB;
  </code></pre>
  
  <p>..., as these were the only classes, using grep, I could find to have a public 'function raw' within them. Query/Builder gave me an error, and Connection run OK but perhaps I didn't build the query object correctly as it gives me inconsistent results from running SQL in MySQL shell. Kinda hit a dead end, can anyone offer any help?</p>
  
  <p>Thanks</p>