Skip to main content
Quick Tip

Filter hasMany relationships

Just a code example from my project, showing the possibility of filtering hasMany relationships.

TagTypes -> hasMany Tags -> hasMany Examples

And you wanna query all the types, with their tags, but only those that have examples, ordering by most examples.

$tag_types = TagType::with(['tags' => function ($query) {
$query->has('examples')
->withCount('examples')
->orderBy('examples_count', 'desc');
}])->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

Roles and Permissions in Laravel 13

14 lessons
57 min

Queues in Laravel 13

18 lessons
1 h 12 min read

How to Build Laravel 13 API From Scratch

30 lessons
1 h 23 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.