Skip to main content
Quick Tip

Order by Pivot Fields

When working with belongsToMany and pivot tables, you can create extra columns in the pivot table. Then, use wherePivot() and orderByPivot() to create a separate relationship function in the Model, already filtered/ordered the way you need.

app/Models/User.php:

public function roles(): BelongsToMany
{
return $this->belongsToMany(Role::class)
->withPivot('active')
->withTimestamps();
}
 
public function latestActiveRoles(): BelongsToMany
{
return $this->roles()
->wherePivot('active', 1)
->orderByPivot('created_at', 'desc');
}

Some Controller:

$users = User::with('latestActiveRoles')->get();

Enjoyed This Tip?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Recent Courses

Laravel Modules and DDD

16 lessons
1 h 59 min

PhpStorm Junie AI for Laravel Projects: Crash Course

7 lessons
36 min

Laravel HTTP Client and 3rd-Party APIs

7 lessons
50 min

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.