This episode is for members only

Sign up to access "Eloquent Relationships By Example" right now.

Get started
Already a member? Sign in to continue
Playing
15. Defining a belongs to relationship

Episodes

0%
Your progress
  • Total: 4h 18m
  • Played: 0m
  • Remaining: 4h 18m
Join or sign in to track your progress

Transcript

00:00
Let's take the example in the last section where we had a list of posts, say post one, post two and post three. We know that each of these have a user assigned to them under the user ID column. So each of these will have been posted by a particular user.
00:20
Now, in the last section, we looked at iterating over posts, but we weren't able to say who owned them posts because we didn't have a reverse relationship to be able to access these. So when we define out a has many relationship or we're just iterating through a bunch of models, we need to be able to hook back into who owns this particular post. Or this could represent any kind of relationship type.
00:47
It doesn't have to be users and posts. So in this episode, we're going to start things out by recreating a very rough example of what we did in the last section. When we looked at one to many, and then we're going to define the inverse of that, which is belongs to. This can get a little bit confusing because when you think about belongs to or a post belonging to a user, you might think that you would reach for the has one relationship type because a post has one user.
01:17
But the way that Eloquent works is it's a lot more efficient to use belongs to. So let's take a look at how this works. I've gone ahead and created out a fresh Laravel project and I've switched over my database credentials. So I'm going to go ahead and run migrate here just to create out our database.
01:33
And let's get started with creating out a post table exactly like we had before. So we're going to go ahead and use Artisan to make our model here and we'll create a post model alongside a migration. And let's head over to the create post table migration on the database and migrations. And let's fill this in.
01:55
So we know that this belongs to a user and that's the kind of key of this section. It belongs to a user. And we're going to say user ID. Now, we can name this differently.
02:05
You don't have to have user underscore ID. This is just the convention. Laravel is very clever in the way that it was specifically with Eloquent. It will detect the column names based on what you're trying to access.
02:18
We're going to cover that in another episode in this section because there are lots of relationships where we can customize the foreign keys that we add. So let's also add in a piece of text here and we'll just say bodies. We'll just keep things very similar. So let's go ahead and migrate these changes.
02:35
And now that we've done that, we can head straight over to our user model under app and models and we can add in this posts relationship. So let's do that and then just start to iterate through a bunch of posts. So we know that a user has many posts. So this is has many.
02:52
And then, of course, we pull in the post model and grab the full namespace to that. And that's pretty much it. That is our basic relationship that we've already covered. And then over in the post model, let's go ahead and just fill in fillable just in case we go ahead and create some of these out in code.
03:11
And we'll just make sure that body is fillable. So we'll be coming back to post, because remember, for each post, we need to link this back to a user. So we'll come over and modify our post model in just a moment. OK, so we're going to go over to our web routes.
03:28
Let's go down here and just use this home page as an example. And we'll go ahead and return out a view in here. And again, we'll keep this the same. We're going to say post index.
03:38
This time, we're just going to grab out all posts, because remember, not necessarily for the currently authenticated user. If we are showing a list of all posts, they are going to be by different users. So that gives us the ability to add in the context of who these posts are by. So let's go ahead and use our latest scope and say get.
03:56
And let's pass these posts down, making sure you just pull the namespace in here. And we'll pass them down to our view so we can iterate through them. So let's go ahead and create this view out. And we'll create a post folder and create index.blade.php under here.
04:15
And this is where we will iterate through these. Now, we don't have any posts or users at the moment. So once again, just while we're testing, we'll go ahead and pull up Tinker and we'll go ahead and use user factory and create. And we're actually going to do this a few times because we're going to have multiple posts that belong to different users.
04:37
So we can actually use the times method in here as well. Let's create three different users out here. So now, if we just exit out of here, we've got three users in the database. Now, we could have created a factory for our posts.
04:50
We will kind of ignore that for now, but we're going to manually create some posts in here for these different users. So let's go ahead and do that before we start to iterate through. So I'm going to go ahead and create out a post from this user here. First post will manually fill in created at and updated at.
05:09
And let's create out a second post and have that by the same first user. So we have one user posting twice. We will create a third post here by user two, and we will create a fourth post by user three. So something like you would actually see in an application where you have multiple posts,
05:32
some of them by the same user and from lots of different users. OK, so over in our index.blade.php file, let's go ahead and iterate through each of these posts as we've already seen. So we'll go ahead and end the foreach there. We'll create our div in here.
05:49
Let's again output the post ID so we just have a reference to this. And let's output the post body just inside of here. OK, so that should, if we head over to just the home page, show us all of our posts. Now, we are scoping them by latest, but we've got the same timestamp here for every single one.
06:09
So don't worry too much about the order just yet. Now, the problem we have here is this is a public page where anyone can see all of the posts in our application. But we don't know who has posted each of these posts. So that is where we then jump in to the post model and we define the relationship back to the user who posted that.
06:31
So let's just take a look at the structure of our database again. A user's table has an ID. Our post table has a user ID. But our post knows who the user is so it can relate back to the user's table.
06:44
So a post belongs to a user and a user has many posts. So let's jump over to our post model under app and models and start to define this relationship out and then see how we access it. So we're going to go ahead and create out a method in here which you can probably guess is called user. Not users because a post isn't owned by multiple users.
07:09
It's owned by just one user. So we're going to go ahead and say this belongs to and a post belongs to a user like so. That's all we need to do for that relationship. We will dive into some of the different arguments we can pass through here in a bit.
07:28
But that's the most basic form. One other thing that we will need to cover here is eager loading, which we're not going to do just yet. We're going to do that in the next section. But this is an incredibly important thing.
07:38
So keep that in the back of your mind. Okay, so now that we've got this user relationship, how are we going to access this? Well, let's go over to our web routes first of all and just die dump on post just to see if anything is different here. So let's go over and give that a refresh.
07:54
We know that we get a collection back with the four posts that we have in our application. Let's just open one of them and see if anything is different inside of here. So we don't have any additional data now that we've defined that relationship. And we don't have really anything else in here that has changed at all.
08:11
The difference now is that for each of the posts that we iterate through, we can access that user in there. So let's just do this within code first of all, and then we'll jump over to our blade template to actually output this data. So I'm going to go ahead and we could do a for each loop in here and just die dump on the first record or we could pluck the first record out. It doesn't really matter too much.
08:33
But let's say for each post as post. So in here, if we just die dump on this post, we know that this just gives us a single post model. Now this post model now has that user relationship on here. So that will perform a query to go back and look up a user where the user ID matches that post's user ID.
08:55
And sure enough, you can see that for the first post here, we get back the user that we would expect. So very easy now to just go back into the user and find out who owns this post. So now that we've done that and had a look at that and die dumped on it, we can do this within our blade template. So up here, I could say something like X posted or X said, and then we can output the contents of the post.
09:21
So to do this, we're going to access the post. Then we're going to access the user. Remember, not as a method, because that's going to give us the relationship class that we can use to build. And we don't want to do that.
09:34
And then now that we're dealing with the user model, we can just access any of the properties on this user. So, for example, their name, email address, whatever you need to output. So, of course, name here kind of makes sense. So let's go over, give this a refresh.
09:48
And there we go. We have this user said first post. This user, remember, we have two of them said second post. And then we have two different users here, each posting their own post.
10:00
So this nicely brings everything together with this belongs to relationship, where now, as we are iterating through a list of things, we can access what this belongs to. So obviously, in our case, a post belongs to a user, but a project, for example, could belong to a company, a deployment could belong to a server. It really depends on what you're building. But if you just think about it in terms of who owns what and how this works in the real world, you can pretty much always translate this back to the relationship type.
33 episodes4 hrs 18 mins

Overview

Eloquent is Laravel's ORM (Object Relational Mapper). In simple terms, it's how your models work with the database.

The good news? There's a bunch of powerful relationship types available. Our task is to learn when and where to use each one.

In this course, we'll cover each basic relationship type, how to access related models, and then insert, sync, update and delete related data. Oh, and we'll build a practical example for each relationship type, to really make it stick.

Alex Garrett-Smith
Alex Garrett-Smith
Hey, I'm the founder of Codecourse!

Episode discussion

No comments, yet. Be the first!