Filter by many-to-many relationship pivot column

If you have a many-to-many relationship, and you add an extra column to the pivot table, here's how you can order by it when querying the list.

1class Tournament extends Model
2{
3 public function countries()
4 {
5 return $this->belongsToMany(Country::class)->withPivot(['position']);
6 }
7}
1class TournamentsController extends Controller
2 
3public function whatever_method() {
4 $tournaments = Tournament::with(['countries' => function($query) {
5 $query->orderBy('position');
6 }])->latest()->get();
7}

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord