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 Pivot20{21 protected $table = 'post_tag';22}23 24// Somewhere in the Controller25public function getPostTags($id)26{27 return Post::findOrFail($id)->tags()->orderByPivot('flag', 'desc')->get();28}
Tip given by @PascalBaljet