In this episode, we dive deeper into working with relationships in our application, specifically how to associate records after creation. We start off by revisiting the typical way you'd create a post that belongs to a user—using the user's posts relationship to quickly create and relate a new post.
But then, we explore a different scenario: what if you want to create a post first (maybe you're building it up in steps) and only later decide which user it belongs to? We walk through the process of manually creating a post (either with make
or create
), and explain why you might pass in the user ID directly, though that's not always the best approach.
The episode then focuses on the more flexible method: using the associate
method on the relationship. We show you how to instantiate a post without saving it right away, look up or grab a user model, and then 'attach' the user to the post using associate
. Once associated, saving the post completes the process, filling in the user_id automatically—no manual assignment needed and no changes required to your model's fillable fields.
Throughout the episode, you see code demos, explanations on when (and why) you might do it this way, and comparisons to the standard relationship-based approach. By the end, you'll have a good grasp on both the "usual" and the "alternative" ways to handle associating models in Laravel (or similar frameworks).