title: Sort belongsToMany relation base on field in belongTo relation Laravel Eloquent
body: <p>I have a scenario where <code>User</code> has a <code>belongsToMany</code> relation with <code>PortalBreakdown</code>, <code>PortalBreakdown</code> has a <code>belongsTo</code> relation with <code>Portal</code>. <code>Portal</code> has <code>order</code> column in it. I have a method <code>listing_quota($id)</code> in <code>UserController</code> which returns all breakdowns of the user. I want to sort these breakdowns based on <code>order</code> column of the portal. Below are the code of classes and a method I have tried.</p>
  <pre><code>class User extends Model {
      protected $table = 'user';
      public function listing_quota() {
          return $this-&gt;belongsToMany('App\PortalBreakdown', 'user_listing_quota')-&gt;withPivot(['quota']);
      }    
  }
  
  class PortalBreakdown extends Model {
      protected $table = 'portal_breakdown';    
      public function portal() {
          return $this-&gt;belongsTo('App\Portal');
      }
  }
  
  class Portal extends Model {
      protected $table = &quot;portal&quot;;
      protected $fillable = ['name', 'description', 'order'];
  }
  </code></pre>
  <p>Below is the method where I am trying to return sorted by order. I tried few things some of which can be seen in commented code but not working.</p>
  <pre><code>class UserController extends Controller {
  
      public function listing_quota($id)
      {
          $user = User::with(['listing_quota' =&gt; function ($query) use ($id) {
              // $query-&gt;sortBy(function ($query) {
              //     return $query-&gt;portal-&gt;order;
              // });
          }, 'listing_quota.portal:id,name,order'])-&gt;findOrFail($id);
  
          // $user = User::with(['listing_quota.portal' =&gt; function ($q) {
          //    $q-&gt;select(['id', 'name',order']);
          //     $q-&gt;orderBy('order');
          // }])-&gt;findOrFail($id);       
  
          return $this-&gt;success($user-&gt;listing_quota);
      }    
  }
  </code></pre>
  <p>I also tried chaining <code>orderBy</code> directly after relation in Model class but that's also not working from me. Thank you in advance.</p>
  <p><strong>NOTE:</strong> I am using Laravel Framework Lumen (5.7.8) (Laravel Components 5.7.*)</p>