title: Laravel - randomly select n number of rows containing same value in certain column after applying 'order by'
body: <p>In my Laravel project, in the database table <code>ads</code>, I have  the following structure :</p>
  
  <pre><code>id | col1 | col2
  </code></pre>
  
  <p>col2 has values like <code>topad</code>, <code>bump</code>,<code>urgent</code> along with empty value. I want to take all the rows from the <code>ads</code> table and sort them alphabetically based on <code>col2</code> in descending order.</p>
  
  <p>So I used:</p>
  
  <pre><code>Ads::orderBy('col2','DESC')-&gt;get()
  </code></pre>
  
  <p>Now I have 2 conditions to be applied on the query.</p>
  
  <p><strong>1st condition :</strong>  Suppose there are 4 rows with <code>topad</code> in <code>col2</code>, 5 rows with <code>urgent</code> in <code>col2</code>, 6 rows with <code>bump</code> in <code>col2</code> and 7 rows  each with an empty value in <code>col2</code> . So  rows with <code>urgent</code> in <code>col2</code> will appear 1st, with <code>topad</code> in <code>col2</code> will appear 2nd and with <code>bump</code> in <code>col2</code> will appear 3rd and with empty values in <code>col2</code> will appear 4th.  Now I need to randomize the rows' order within each set. For example , rows with <code>topad</code> in <code>col2</code> may have the <code>ids</code> 1,2,3,4. I want to randomize these rows (which may result into for example 4,2,1,3). But they will appear before rows containing <code>topad</code> in <code>col2</code>. Same is true for <code>topad</code> and <code>bump</code> row sets and rows containing any empty  value in <code>col2</code>.</p>
  
  <p>So the query becomes :</p>
  
  <pre><code>Ads::orderBy('col2','DESC')-&gt;inRandomOrder()-&gt;get(); 
  </code></pre>
  
  <p><strong>2nd condition :</strong> Suppose rows are ordered by <code>col2</code> values. But from each set of rows containing same value in <code>col2</code>, I need <code>n</code> number of rows from those that have non-empty value in <code>col2</code> i.e. <strong>randomly</strong> I need  <code>n</code> rows from <code>urgent</code>ed rows, <code>n</code> from <code>topad</code>ed rows, <code>n</code> from <code>bump</code>ed rows  and <strong>all</strong> from <code>empty</code>ed rows. </p>
  
  <p>How to write the query then ?</p>