In this episode, we dive into two different ways to insert related data into a database, specifically focusing on creating posts for users using Eloquent relationships.
First up, we look at the standard way (and the one you'll probably use 99% of the time): simply creating a new post through the relationship using the create
method. This approach is super straightforward—just pass an array of data, and Eloquent handles linking the post to the user by filling in the user ID for you. We walk through setting this up, including making sure your Post
model has the necessary fields marked as fillable (like the body
). We then test it out by creating a couple of posts and exploring how they show up as a collection related to the user.
Then, we switch gears to explore an alternative method. If you need to do something special with your post model before saving it (like modifying fields or setting up relationships), you can use the make
method to create the post, tweak as needed, and then persist it to the user's posts with the save
method. We test this out and talk about some situations where this approach might be necessary, such as when you need to manipulate the model or set up more complex relationships before saving.
By the end of this episode, you'll have a good grasp on both methods and know when to use each. Next time, we'll look at iterating over these collections and displaying the related data. Stay tuned!