In this episode, we dive into attaching related models—specifically, how to attach topics to a course in Laravel using Eloquent's relationships. We start off by getting hands-on with a bit of code to attach a topic directly to a course using the attach
method. If you've ever wondered how to hook up two models that already exist (without creating new ones), you'll see how straightforward it can be.
After the quick coding demo, we transition to building a very basic UI for this feature. We set up a couple of routes: one for displaying a list of topics you can attach to a course and another for handling the actual attach action via a form submission. You’ll see how to structure your form to submit the selected topic ID, how to process the request to connect the models, and how to do this all with just a touch of validation (and a reminder to add more robust validation in real-world scenarios).
You'll also get a quick walkthrough of some common pitfalls—like what happens if you pass an invalid ID, why validation matters, and how Eloquent helps you out with methods like findOrFail
and validation rules. By the end of this episode, you'll have both a programmatic and a super simple UI example of how to let users attach relationships between models in their own Laravel projects. Next up, we'll cover how to remove these relationships when needed!