Playing
02. Creating and accessing the relationship

Episodes

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

Transcript

00:00
In this section, we're going to look at the most basic relationship type,
00:03
which is one to one, and in this particular example, we're going to say that a user has an address, just one address on our system that we can access, update, delete, whatever we need to do. So I've gone ahead and got started with a completely fresh Laravel application here,
00:21
and I've got this open in the browser. I haven't set up my database yet, so if you are new to Laravel, we'll take this part just to go through this again. So I'm going to go ahead and open up our main EMV file in our root directory here,
00:35
and I'm going to go ahead and switch over my database credentials to hook this up to my database. And of course, this is going to be different for everyone. I've already gone ahead and created the database just over here,
00:47
but I haven't run the migrations yet. So that's the first step. Let's go ahead and run php artisan migrate, and that's going to go ahead and run the default migrations that we have here.
00:57
And the users table really is what we're interested in. And of course, we're going to be creating another table that will hold these users addresses. OK, so we are going to start out by creating an address model.
01:12
So alongside of that, we can also create the migration, which will create the database schema for us. So let's go ahead and say php artisan make model. And we're going to call this address.
01:24
We're then going to use the M flag, which will alongside the model also create a migration for us. So let's run that. You can see two files have been created, the address model and the migration.
01:37
So we're going to head over to the migration. First of all, these exist in the database directory under migrations. And we're going to come down here and just open this up and fill in the data that we want.
01:49
So the first thing we need to figure out is who does this address belong to? It could belong to any model. But in our case, the user is going to have an address. So the first thing that we need to add to this is a user ID.
02:02
So we know who this address belongs to. So there's a couple of different ways that you can do this. But a convenient way would be to use the foreign ID method and then give the column name for this.
02:14
So this is going to be called user ID within this table. And Laravel will automatically hook this up to the users table for you. You can also use the constrained method on this, which will automatically create a foreign key.
02:29
Basically, if you try to insert a user ID into this table that doesn't exist on the users table, it just won't work. OK, so now that we have a user ID in there, let's go ahead and add the actual address information.
02:43
So for an example, we might have a line one. We might have a line two. We might have a postcode or a zip code. I'm just going to keep things really simple here
02:53
and just have one piece of data in here. But of course, in reality, you would want to add more. OK, so now that we have filled in our migration, we can go ahead and run PHP Autosyn Migrate again.
03:05
And that's going to go ahead and create that table for us. Let's head over to the database, give this a refresh. And you can see, sure enough, we have the addresses table in there with the user ID, the line one, and we automatically have created
03:17
that and updated that added in for us, which are just the timestamps of when this was created. Or of course, if we update this, it will give us the updated time. So now we need to define this relationship.
03:30
Just before we do that, let's head over to our web routes and let's go up here and create out a new route so we can just use the home page for this. We're going to return a view which will display the user's address.
03:44
So let's go ahead and create out a new view so we can see this. And of course, at the moment, we're not going to be able to access this because we have no relationship defined. So I'm going to go and create out a new file in here
03:56
called address.blade.php. And now that we've got that, we can go ahead and return a view with that address and we can pass any data that we need down to here. We just head over to the home page and give that refresh.
04:11
That is now our empty view where we're going to show the current user's address. So let's, first of all, access a user and then pass that down to this view just before we go on to define the relationship. This will kind of build up the fundamentals of what we're doing in this section.
04:28
So you'll notice that over in the users table, we don't have any at the moment. We're working with a really plain Laravel application here. We don't have any kind of starter kit, so we don't have any way to register a user. So the way that we can get around this is to just do this
04:42
manually with PHP Artisan Tinker. Now, each of your models in your Laravel application by default will have a factory. If you're creating a new model, you can define a factory as well.
04:56
Let me just talk to you about that really quickly, because this is a really important concept within Laravel. So under the database section, under factories, you can see that we have this user factory.
05:06
What this factory allows us to do is define out fake data when we're testing or when we're just seeding our database with stuff to test it out. So what we can do is we can generate out a fake user really quickly without having to manually insert this into the database.
05:22
So let's go over to the command line wherever you're using that. We're going to run PHP Artisan Tinker, which will boot up a session which allows us to run code within our Laravel application without having to write any real code.
05:36
So we're going to go ahead and reference the user model. We're going to use the factory method here, and then we're going to use the create method. What that will do is it will just create out a fake user for us in the database.
05:48
And if we head over, sure enough, you can see that that user has been created so we can reference this user within our code by its ID or email, whatever we want to use, and then we can create addresses for this fake user. So let's exit out of this Tinker session, clear out our console,
06:05
and let's head over to the user model to start defining out this relationship. So at the moment, inside of our user model, if you're very new to Laravel, you can see that this contains things like fillable, which we'll be covering in this course hidden,
06:18
which we don't really need to know in this context and things like casting. So we're going to go ahead and define out the first relationship here, and that will be that this user has one address. So we're going to go ahead and just create out a method in here called address.
06:32
And then from here, we can return the relationship type. So within Laravel, we're going to go ahead and return this has one. And then we're going to give the fully qualified namespace to the thing that this has one of.
06:47
So in reality, this would be app models and address like so. And then we would go ahead and grab the full class name to that. Now, really, what we want to do is just get rid of the app models part. And we want to import this at the top.
07:05
Now, my editor does this automatically. If I hit this, you can see that at the top of the page, this has gone ahead and potentially imported. Let's just have a look here.
07:14
Well, it hasn't because it's in the same directory. But if you were in a different directory, you would do something like use app models and address. Now, we don't need that because we are working within the same directory here.
07:26
But otherwise, you would have to import that. So let's get rid of that and come back down to where we've defined this out. And this is pretty much all we need for a has one relationship. So let's go ahead and access the address that a user has.
07:38
So we're going to head back over to our web routes and we're going to pluck this user out of the database by their ID. So we're going to say user. And that's our model find one.
07:50
So we're grabbing the first user in the database or the user with an ID of one. Once again, I'm going to go ahead and import this at the top of the page. You might need to do this manually if your editor doesn't support it. You just want to pull this namespace in like so.
08:04
OK, so now we can go ahead and pass this user down to our view and start to access that address relationship. So let's go ahead and pass down this user. And that's pretty much it.
08:15
Let's head over to the address.blade.php file. And let's just dump out the user's name. So let's say user and name. And if we come over and give that a refresh, sure enough, we see the name of the user.
08:29
What we want to do is access this relationship. How do we do this? Well, we go ahead and give the name of the method that we have defined. Now, it's really important when we're working with relationships
08:41
within our blade templates or wherever we're outputting this data that we don't use a method call for this. We just head over and give that a refresh. You can see that we do actually get an error here.
08:52
Method calls are reserved for when we want to perform an action on a relationship, not necessarily access that data. So if I were to say user address like a property, which isn't actually like a method we've defined here, what we're actually going to see at the moment
09:08
is nothing because we don't have an address associated with that user. Just for now, we're going to go ahead and create this manually out in the database over in our addresses table just to see what we get. And then we can go ahead and look at creating them in the next episode.
09:22
So I'm going to go ahead and create out a new record in here with the user ID of one. You can input that manually. And let's go ahead and create out a line one.
09:31
Now, for the created and updated app, because we're doing this manually within the database, we probably want to use the now function within either MySQL or Postgres and save this out. You can see that's inserted the current date and time.
09:45
So now technically, this user has one address because we have a user ID in here relating back to that user. Let's go over and take a look at what we get output on the page. Now, this might seem a little bit weird, because really what we're doing here
10:00
is in a blade template when we're accessing that entire address object, we're just dumping this out on the page as JSON. So it's been JSON encoded and it gives us probably too much information here. So what we're going to do is from this particular address,
10:18
we're going to then access the data that we need. So in your templates, when you're outputting the relationship data, you just want to access these like properties. So there we go.
10:27
You can see that for that particular user that we have chosen, we can now access that user's address and we can access any data on that address as well. A really important thing to note here is if we are trying to access properties
10:42
of an address that hasn't already been created, address will technically be null inside of our blade template. We didn't see anything, but the actual value of this is null. We can demonstrate that by going over to our web routes
10:55
and just going ahead and dying and dumping on user and address. And if we come back over here and give that a refresh, sure enough, we get back an address model with all the data that we have with inside of that record.
11:08
But if we were to go ahead and delete this address and save this out, you'll notice that this is null. That means that if we were to try and access within our templates, the address line one, we are technically trying to access
11:23
a line one on a null value, which of course is not going to work. So there's a couple of ways around this. You can either use a null safe to get around this and it will just output nothing. Or you can go ahead and wrap this in an if statement.
11:37
It's probably a little bit clearer to do this. So we're just going to check if the user does have an address first of all. And then down here, we're going to go ahead and end that if statement. And if we head over, sure enough, that works.
11:49
Let's go ahead and just recreate out an address really quickly. Match that up to this user. Go ahead and hook this up with a created app and updated at timestamp. And if we head over, sure enough, that now works.
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.