Order by Pivot Fields

BelongsToMany::orderByPivot() allows you to directly sort the results of a BelongsToMany relationship query.

1class Tag extends Model
2{
3 public $table = 'tags';
4}
5 
6class Post extends Model
7{
8 public $table = 'posts';
9 
10 public function tags()
11 {
12 return $this->belongsToMany(Tag::class, 'post_tag', 'post_id', 'tag_id')
13 ->using(PostTagPivot::class)
14 ->withTimestamps()
15 ->withPivot('flag');
16 }
17}
18 
19class PostTagPivot extends Pivot
20{
21 protected $table = 'post_tag';
22}
23 
24// Somewhere in the Controller
25public function getPostTags($id)
26{
27 return Post::findOrFail($id)->tags()->orderByPivot('flag', 'desc')->get();
28}

Tip given by @PascalBaljet

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