title: Laravel groupby min/max filter grouped results
body: <p>I've got a Laravel query working the way I'd like with <code>min()</code> and <code>groupBy()</code>:</p>
  
  <pre><code>$certificates = CertificateRecord::whereHas('learner', function($query) use($user) { $query-&gt;where('user_id', '=', $user-&gt;id); })
  -&gt;selectRaw('*,min(type) as type')
  -&gt;groupBy('certificate_template_id')
  -&gt;with('issuer','certificateType')
  -&gt;paginate(10);
  </code></pre>
  
  <p>But when I add this to the mix...</p>
  
  <pre><code>-&gt;when($request-&gt;type, function ($query) use ($request) {
      return $query-&gt;where('type', '=', $request-&gt;type);
  })
  </code></pre>
  
  <p>The previously grouped results are somehow ignored while performing this <code>where()</code> and it returns all ungrouped rows.</p>