In this episode, we dig into how to filter by intermediate (pivot) columns in a many-to-many relationship in Laravel, using a real-world use case: displaying courses for a specific topic and a specific version (like Laravel version 9 or 10).
We start by updating our topics page so that you can pass a version
in the query string, and only get back courses matching that version for the chosen topic. You’ll learn how to modify the Eloquent relationship query and apply a wherePivot
filter for precise control. We also talk through the practical difference between eager loading in the route/controller versus doing it inside your template, and cover how this affects query count and code clarity.
Finally, we end with two approaches to the problem—either by fetching the filtered courses and passing them separately, or by eager loading with a constraint using a closure. You’ll see a few common mistakes and how to resolve them, all while making sure your filtering is efficient and clear. By the end, you’ll understand when and why to use each method, and be able to filter your relationships with confidence!