The ordering methods mentioned above did not work for me using Laravel 5.6
However, I found a solution to orderBy a relation model using counts.
I wanted to order my business listings by their membership_level:
- Premium Plus
- Premium
$businesses = Business::withCount('subscription_premium_plus')->withCount('subscription_premium_plus')->orderBy('subscription_premium_plus_count', 'desc')->orderBy('subscription_premium_count', 'desc')->get();
Then I had two methods in my Business model:
public function subscriptionPremiumPlus()
{
return $this->hasOne('App\Subscription')->where('end_date', '>', Carbon::now())->where('membership_level', 2);
}
public function subscriptionPremium()
{
return $this->hasOne('App\Subscription')->where('end_date', '>', Carbon::now())->where('membership_level', 1);
}
My personal code actually included another relationship, but I have simplified things so you get the basic idea of what I did. Using the custom relationship methods also allowed me to add conditionals, such as checking whether the subscription was still valid.
I found this solution much more preferable because it meant I didn't have to right raw mysql code and could continue using Eloquent, which is very pleasant to use.