In this episode, we dive into many-to-many relationships in Laravel and why you'll probably need them as your app gets more complex. We take the practical example of courses and their topics: each course can have multiple topics, and each topic can belong to many courses. Think of it like being able to tag your courses with as many relevant topics as you want, and on the flip side, listing all the courses under a specific topic.
We start by setting up two separate tables: one for courses and one for topics. After building those out, we realize there's no direct connection between them, so we introduce a pivot table (called course_topic
), following Laravel's conventions. This intermediate table lets us link any number of courses to any number of topics, giving us a ton of flexibility.
We go through the process of defining the relationship on the Course model using belongsToMany
, which makes retrieving the related topics super straightforward. There's also a demo of displaying both courses and their topics in a Blade view, so you can see the many-to-many relationship in action.
Towards the end, we talk about the power and reusability of this relationship pattern—you could reuse topics for blog posts or anything else. Plus, we mention how to customize the pivot table's name if you ever need to. For now, we've been manually adding data, but in the next episode, we'll look at how to handle these relationships within your code for a much smoother developer (and user!) experience.
By the end of this video, you'll have a solid understanding of many-to-many relationships, their setup, and how to show them in your Laravel app.