In this episode, we dive into defining a belongsTo
relationship in Laravel's Eloquent ORM, using the familiar user and post example. We start by revisiting how each post has a user_id
, which ties it to a particular user, but up until now, we've only set up the one-way (has many) relationship.
We kick things off by scaffolding a new Laravel project, running our migrations, and setting up the necessary models and database structure. You'll see how to quickly create posts and users using factories and Tinker, so we have some test data to play with.
Then, we add a hasMany
relationship to the User
model and go over how to display posts in a Blade view. But the real focus is on flipping this relationship by adding a belongsTo
method to the Post
model. This step lets us access the User
directly from a post, solving the problem of not knowing who posted each entry when looping through posts.
We show this in action, both in code (via die-dump checks) and in the Blade template itself, so you get to see how to output the user’s name for each post. We also clarify the difference between calling the relationship as a method (if you want to work with the relationship object) and as a property (to get the model itself).
By the end of the episode, you'll not only have working code for showing which user posted each post, but a solid understanding of how belongsTo
works and fits the real-world "ownership" relationships that come up in Laravel projects. Next time, we’ll look at some optimizations like eager loading to make these relationships even more efficient.