title: Order Query by related table in laravel
body: <p>I want to order a query in laravel ways depending on certain factors. One of which would be a related table. </p>
  
  <p>So right now my query goes like this:</p>
  
  <pre><code>$products = Product::where("price", "&lt;=", $maxBudget)   
  </code></pre>
  
  <p>and I know that I can add a function to my where clause like so</p>
  
  <pre><code>-&gt;where(function ($q) use($mature) {
      if ($mature == "1") {
          $q-&gt;where('mature', 1)-&gt;orWhere('mature', 0);   
      } else {
          $q-&gt;where('mature', 0);
      } 
  })  
  </code></pre>
  
  <p>however I want to make a function for my order as well. Something like this (I know this is wrong, this is just an example):</p>
  
  <pre><code>-&gt;orderBy(function ($q) use($orderBy) {
      if ($orderBy == "price_low") {
          $q-&gt;orderBy('price', 'desc');
      } elseif ($orderBy == "price_high") {
          $q-&gt;orderBy('price', 'asc');                    
      } elseif ($orderBy == "rating") {
          $q-&gt;orderBy( $product-&gt;user-&gt;getAvgStarRating(), 'desc')
      } else {
          $q-&gt;orderBy('created_at', 'desc');
      }
  })      
  </code></pre>
  
  <p>The <code>$q-&gt;orderBy( $product-&gt;user-&gt;getAvgStarRating(), 'desc')</code> is obviously wrong, $product isn't even defined, but you get the idea. In this scenario, I'd like to order my query based off the average rating of the creator of the product.</p>
  
  <p>So my questions are: How do I make it so that I can add a function of some kind to my ordering, and how can I order a query based off related tables?</p>