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 on Laravel Daily
[NEW] Mobile Apps: React Native vs Flutter vs NativePHP?
8 lessons
55 min
Practical Laravel Security: Packages, Secrets, Supply-Chain Attacks
7 lessons
43 min read
Laravel 13 Starter Kit Teams and Customizations
10 lessons
33 min