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
10. Accessing the relationship data

Episodes

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

Transcript

00:00
So over the last couple of parts, we've built up a few records inside of this user's post relationship. Now, how do we access these? How do we iterate through them and start to output data? Well, let's just take a look at this, first of all, in our web routes, and then we'll create our view, which will allow us to see this.
00:18
So let's use this just here. And we already know that when we die dump on the post relationship, we get back a Laravel collection. A Laravel collection is just a collection of any items. It doesn't need to be models.
00:31
Collections are incredibly powerful within Laravel. But what this does allow you to do is iterate over these. So what we could actually do here is switch out this die dump for a foreach, much like we would just do in plain old PHP. And we would say for each of these posts as post.
00:48
Now, as we iterate through these, what is going to happen is because a collection has the ability to be iterated over, each of these posts here is now going to be a post model. So what we can do is we can just dump as normal on each of these posts and just see what we get. So let's give this a refresh.
01:07
And sure enough, we now have three instances of a post model. And we already know through our practice in our want one section, we can just access any of the attributes on these to do something with them or display them out to the user. So we can iterate over these. There are also some other really helpful methods on a collection.
01:29
For example, we can grab a count. Notice we're not accessing the relationship type here. We're actually just accessing the collection. Count is a method on a Laravel collection, which will give you back how many items there are in there.
01:43
And sure enough here, you can see there are three. So you can even use these within your views to show how many posts we have. And we can do that as well. So let's go ahead and just create out an endpoint, which renders out of view.
01:56
So we can actually look at practicing outputting this data. So let's go ahead and create out another route in here called just posts. That would do. And we'll just do this all directly within here and won't use a controller just yet.
02:09
Let's go ahead and grab that first user, that fake user that we created. And then let's return a view in here. And we'll just call that posts index. And we're going to pass through either the user or the posts.
02:22
Now, most of the time, you'll just pass the posts through because we don't necessarily need access to the user. So we could do this all in line here. We could define a new variable if we wanted to. But that is probably the easiest way to do it if you were just outputting a list of this specific user's posts.
02:38
So there we go. We've passed them down to our view. We don't have that view yet. So let's head over to resources, views.
02:44
Let's create out a posts directory and an index.blade.php file. And let's start to iterate over these. So let's go and use a blade for each here to say for each posts as post. Posts is still a collection.
03:01
And now for each iteration here, post will be a post itself. And then we can just end the for each loop there. So instead of accessing these directly like posts and body, which we can't do because post is a collection, not a model. Now, now that we're iterating through these, we can go ahead and access this data from post.
03:22
So here, let's output the post ID just so we can see what we're doing. And then just after this, let's output the post body so we can see each one. So now if we head over to slash posts, we will see a list of our posts. And we did delete one.
03:38
So the IDs don't quite match up here. That's why. But we are getting a list of these posts. Now, let's talk about ordering these because it is always going to be a really important part of listing through any data.
03:52
Now, at the moment, these are not ordered by their created at date. There's some ordering that goes on behind the scenes. But basically what we want, let's say, is the latest post at the top. That kind of makes sense for something like this.
04:06
At the moment, the latest post is going to be on the bottom just because of the ordering that we have added this into the database. So how do we order these? Well, we don't do this at this level. We can actually order stuff within Laravel Collections.
04:19
But that is absolutely not what you want to do unless you have a very specific use case. You want the ordering to happen at the database level. So how do we do this? Well, let's go ahead and just bring up our posts to a new variable just so this is a little bit cleaner.
04:34
And let's access user posts here. And then let's just pass posts down to here. So let's go over, give that a refresh. We get exactly the same thing.
04:43
But now we've got a little bit more room to breathe here, and we can go ahead and implement ordering here. So effectively, what we want to do is build up the ordering behind the scenes in the query that gets sent to the database. What we can do is on a collection, we can sort by a certain column. So you could sort by created at if you wanted to.
05:04
Let's just take a look at what that gives us. Nothing at the moment because we can do things like sort by descending. And let's give that a refresh. You can see that that has changed.
05:13
But this isn't really what we want to do because we're doing this within the collection itself, not at the database level. We want the database to give us back these in the correct order. So what we want to do instead is access the actual relationship itself so we can continue to use Laravel's query builder to build this up. Then we want to go ahead and use any of the methods that exist on Laravel's query builder.
05:37
And these are all in the documentation. There are loads of things that you can do here. But we want to use an order by. So we're going to go ahead and order this by the created at date, and we're going to do that in descending order.
05:49
So the first argument is the column. The second argument is the direction that you want this to go in. Now, what's going to happen here? Let's head over and just give this a refresh.
05:58
And you can see that we don't actually get anything here. Why is that? Well, what's actually happening here is we are technically still dealing with a query builder. Let's demonstrate that by dying and dumping out on posts here and just having a look.
06:13
So you can see that we've still got this has many relationship type that's still building stuff up behind the scenes for us to go ahead and chain on more methods here if we want to. So, for example, we could add a where clause in here if we needed to. There's a ton of things that you could do. But what we want to do is get back all of the records once we are done building everything up.
06:35
So to do that, we go ahead and use get. So that's going to give us back, again, a collection of all of these records. But now with this new builder stuff that we've added, added in. So if we just die dump on posts here really quickly to have a look at this, sure enough, we get back a collection.
06:53
The difference now is the first record here is the third post. Remember, that was the last one before. This is now kept that order based on what we're getting back from our database. So if we just give this a refresh, sure enough, this is now the order we want.
07:08
But the query has been done and performed at the database level and ordered it there, which is a lot faster than doing this within your code, particularly if you have lots and lots of records. So just before we move on, there is a slightly different way that we can do this. Laravel provides query scopes, which we're not going to go into too much detail with. But these are things that build up things like an order by behind the scenes.
07:33
You can create your own ones of these as well. And we have courses on that. But doing order by created and descending is a lot easier by just saying latest. Now, behind the scenes, latest will do exactly what we've just done, but it reads a little bit better in your code.
07:48
So most of the time you'll see things like latest or oldest, which will, again, change that background to the oldest at the top. And you can just use this instead. So that's a little bit more convenient. Now, another thing that you can do with this is if you did want to just get the first post, you could use first.
08:07
Now, first is not at the database level. This will still return to you all three of these posts. But first exists on the collection itself. So if we just go and just give this a refresh and you can see we get an error.
08:21
If we just die dump on posts here and give that a refresh, you can see we just get one. Now, actually, I've just said that this happens at the collection level. It doesn't. What you can do is say get.
08:35
So that will get back a collection of all of our items. And then we'll grab the first one. So you can see we get exactly the same thing. Now, this is a really important distinction to make when you're working with Laravel and Eloquent.
08:47
Whether you're performing an action on a collection, which is generally a lot slower, or at the database level. Now, get, remember, returns a collection. So now we're using the first method on a collection rather than at the database level. If we were to get rid of get and we just do first on our builder, this will add a limit on our query to one.
09:09
So in the case of grabbing the first record, we really just want to use first. But let's go ahead and switch this over to exactly what we actually need to get this working, which is the following. Grab the relationship, order it, and then grab the collection. And we end up with exactly what we need.
09:25
So just to finish off, let's look at over in our index.blade.php file in here, just listing out how many items are in this collection. And remember, we're using a collection method here. So we're going to go ahead and say posts and count. And at the top of here, if we just wrap this in a div really quickly, that's going to give us how many items we have in total,
09:47
which we could put into a sentence to show the user. Now, it's worth knowing at this point, this isn't the most efficient way to do things, but it's perfectly acceptable depending on how many records you have. There are aggregates you can build up and you can count at the database level as well, which we won't do just yet. But this is enough for now to show this.
10:06
So we could say there are, and let's put this within the div, there are X amount of posts, which is just going to be the count. And we could say the following, there are three posts. And of course, we see three posts on the page. Now, as a little bonus tip, if you are just learning Laravel and I get rid of all of these except one, you can see that we get there are one posts.
10:30
That doesn't quite make sense in terms of the grammar of this. What we want here is a plural. So we can actually go ahead and say string, which is a helper in Laravel, and we can use plural. The first argument we pass through is the singular version of this.
10:46
And the second argument we pass through is the count. And behind the scenes, this will go ahead and determine whether it should show post based on the count or posts based on this. So if we give this a refresh now and yeah, that's just a posts count. And have a look, there are one post or there is one post, but you kind of get the idea.
11:06
Let's just change this around because it's going to get too complicated otherwise. And we'll just say one post. And let's go ahead and just insert another one by going back to create in here. And it's going back to the home page and back to our posts page.
11:22
That's the one that we're building. And you can see two posts. So I think that's enough now for accessing the relationship data, because we're going to have a look at how we can do this in the practical example at the end of this section. But once again, the majority of the time, you're just going to be passing data down to your views like this, potentially adding some sort of additional query to this, like how we want to order this and then just passing them down to the view and going ahead and iterating through them.
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!

Comments

No comments, yet. Be the first to leave a comment.