title: Laravel eloquent: search by tags with orderBy on found tags number
body: <p><strong>Hi!</strong></p>
  
  <p>I have a relationship: ManyToMany between tags and snippets (through a pivot table: snippet_tag).</p>
  
  <p>I want to make a search by tags on snippets list. The issue is, how to order the search results by the number of found tags.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>        $tags = explode(" ", $tags);
          $snippets = Snippet::whereHas('tags', function ($q) use ($tags, $tags_db_table) {
              $q-&gt;WhereIn($tags_db_table.'.name', $tags);
          })-&gt;paginate(10);
  </code></pre>
  
  <p><strong>In the example below, I have 4 tags which gave 5 results:</strong></p>
  
  <p><em>1st snippet: 1 tag found (green tags)</em></p>
  
  <p><em>2nd snippet: 3 tags found (green tags)</em></p>
  
  <p><em>3rd snippet: 2 tags found (green tags)</em></p>
  
  <p><em>4th snippet: 2 tags found (green tags)</em></p>
  
  <p><em>5th snippet: 2 tags found (green tags)</em></p>
  
  <p><strong>How to make 2nd snippet appear first (3 tags found) and 1st result appears last (1 tag found)</strong></p>
  
  <p><strong>Thanks!</strong></p>
  
  <p><img src="https://i.stack.imgur.com/UWbjY.jpg"></p>
  
  <p><a href="https://i.stack.imgur.com/UWbjY.jpg" rel="nofollow noreferrer">Search by tags with eloquent</a></p>