Laravel 5.8 – From The Ground Up - Laravel 5.8 Tutorial From Scratch – e45 – Eloquent Relationships One To One (hasOne, BelongsTo)

Education, Programming

Laravel 5.8 – From The Ground Up

52 Lessons

Laravel 5.8 Tutorial From Scratch – e45 – Eloquent Relationships One To One (hasOne, BelongsTo)

next up let's start talking about some of the relationships available in eloquent and of course eloquent is our database Oh RM in relationships are an

integral part of any relational database so the first case we're going to handle is a one to one case one to one case is a little bit rare you don't get a lot of opportunity to use this however when you

need to use it it's definitely an important one to know now the example that we're going to use today is a user has one phone so that's what we're gonna be writing in our code so this is a

fresh laravel installation right now I haven't done anything except set up our database and right now our database doesn't contain anything at all all I did was migrate what comes with laravel

let's jump into our code and check out what I want to do so if we open up app of course we have the user model this one ships with laravel so I want to add a new model and the model is gonna be

for a phone so let's jump into the terminal and let's say PHP artisan make me a new model called phone and give me a migration we're gonna use the – M flag for that and so it creates a migration

and a model alright so back to phpstorm we have now this phone and all I will do here is just set my fillable fields to an empty array we've covered all of this before in the series so this is just a

very quick review now let's go to the create phone's table and let's create our table here so what does it need well for a phone of course we need a phone we'll save that to a string and we'll

save phone and for a one-to-one relationship each record in the database needs to reference our user so we can make them connect and we do that like so we'll say table unsigned integer and

then we reference the model so the model that we're talking about is the user model now naming convention in laravel is that you will type the model name say user all lowercase singular underscore

ID if you follow that naming convention then everything will work without you having to make a lot of changes so user underscore ID and then we can say me an index on that and typically you're

gonna want to index any of the foreign keys and that's it we can close that line now additionally you might want to set up a foreign key and so that's done in the following manner

so we'll say this table has a foreign key using the user underscore ID column now that column references what does it reference well it references the ID column on our users table so that's

gonna set up a foreign key at the database level so not only at the PHP level but we're setting it up at the database level as well so now let's hook all of this up each of these two models

is gonna need some sort of reference to each other so let's start with the user so we said that a user has one phone so let's do that now we'll say public function phone and notice here this is

singular for our model name and we're simply gonna return this has one and of course what does it have it has a phone class and that's it now to set up the inverse of this let's go to the phone

model and in the phone model we'll say public function so this phone has a user so we'll say that as returned this belongs to a user class does that make sense

so in our user model of course our user has one phone and then in our phone we'll say our phone belongs to the user so just to clarify here the table that has the reference in this case the user

ID reference is the one that gets the belongs to now the table that you are referencing is the one that gets the has one method so keep that in mind whenever you're setting up this relationship

alright perfect so let's put this to work let's go to my routes file just as a quick playground and let's delete all this and all I want to do is this let's say that we have a phone and we'll do

that by calling new app phone so now we have this phone now the phone let's go ahead and give them a phone of one two three one two three one two three four great so now

or you can do this you can save phone go ahead and explicitly pass in the user ID but I don't really want to do that what I want to do is I want to save through the relationship and I'll show you how

to do that so to save through the relationship let's do the following let's whip up a new user and we'll say factory app user class create a user force

all right so create a new user force and save it to a variable and then down here we can say user and then we can reference that phone relationship so say phone and then save this phone that we

just created this will assign that user ID for us without us having to do it by ourselves all right so let's test this out in the browser let me jump to Chrome and I'm

just gonna refresh this page and it looks like we forgot to migrate our database let's do that now PHP artisan migrate and we get some sort of error I bet you I know what it is let's go back

to our phones table so this unsigned integer level and recent versions actually change to big integer so it needs to be unsigned big integer that way it matches the size that potentially

the user ID could actually be let's try that again then PHP artisan migrate it says the phone already exists so we actually need to run PHP artisan migrate fresh and there we go

so we're good to go so we can go back hit refresh on this page and now that relationship should have been created for us let's check out table plus hit refresh so we have these phones and of

course we do have that user ID associated already with our phone let's jump back into the terminal and run tinker PHP artisan tinker so let's do something let's grab our phone by just

running app phone and give me the first one so we have our phone so how do we get the name of the user will grab phone and then we can get that user relationship if we run it just like that

we get the entire app user however if we just want the name then we can say user and then another arrow and let's grab their name and that's the name of that person now let's run the inverse so if

we have a user let's grab our user app user and give me the first one so we can grab the user's phone and that's the relationship there we go and if you just wanted their phone number then we can do

the same thing and we're gonna have to put another one and just say phone and there we are then we get the phone number for them so that's how you retrieve and safe there is a shortcut

for creating so let me show you that now phpstorm back to my web browser so here's the shortcut we have our user instead of doing all of that you can actually say

user and then grab that phone relationship but this time we're going to put the parentheses and then you can call the create method a lot like we've been doing before so we can pass an

array here and save phone we'll just say to do 2 3 3 3 4 5 6 7 phone not phone got it alright so let's try this one now let's go back to the browser just hit refresh says that we have a mass

assignment issue in our phone looks like I forgot to set that let's fix that error back to my phone we'll just say phone is fillable of course you could also say guarded equals empty array

instead both will do the same exact thing all right so let's go back hit refresh and there we go so now we go back to table plus we should also have a second record and we

do have that user with ID of 3 and there it is this is the user that is associated with that phone so that's a nice little shortcut that you could do to create through a relationship so

whenever you want to create something you can call the relationship on it notice that it does have the parentheses and then you could call the create method on it and then in this manner of

course notice how the user ID is not actually being passed in levels taking care of doing that for us so the last thing I want to do is I just want to push this up to github that way you guys

can have access to this code in right here I have this repo set up I'm gonna hit refresh and now you have this 101 branch that you can play with and what you can do is you can compare

between one and the other and this will only show you the difference between the base layer and what we added to make this work so it's a really nice and convenient way for you to see what I did

with the coat so with that being said that's one one relationships in layer Bo

Eloquent offers a simple way to declare database relationships. In this episode, we are setting up a one to one relationship between a user and a phone.

For the best experience, follow along in our interactive school at

Code for this Lesson

DigitalOcean Referral

Course Source Code

Hit us up on Twitter with any questions or comments @codertape (

About This Course

Ready to get started on your path to Laravel Artisan? In this series, we are breaking down all of the basics of Laravel to get you comfortable using the world’s most popular PHP framework. Let’s get started!

    add to database laravel admin laravel artisan Artisan Command artisan commend create artisan console artisan laravel command authentication in laravel belongsto belongsto laravel example coding tutorials create artisan command create command artisan create new command artisan Create your own crud laravel crud laravel tutorial crud resource laravel crud with file upload custom artisan commands custom artisan commands laravel custom laravel database configuration laravel database relationship digital ocean dotenv eager loading eager loading in laravel eager loading vs lazy loading laravel eloquent eloquent accessors eloquent mutators eloquent orm feature testing laravel fetching data in laravel filesystem laravel form requests full stack vue gate and policy laravel google optimize hasmany hasmany laravel hasmany laravel example hasmany relationship in laravel hasone hasone relationship in laravel How to create how to queue email how to use queue installing laravel intervention image laravel laravel 5 laravel 5 auth laravel 5.4 queue laravel 5.5 queue laravel 5.8 laravel 5.8 artisan command laravel 5.8 artisan console laravel 5.8 auth tutorial laravel 5.8 authentication laravel 5.8 commands laravel 5.8 crud laravel 5.8 crud example laravel 5.8 custom middleware laravel 5.8 deprecations laravel 5.8 eager loading laravel 5.8 elixir laravel 5.8 event listeners laravel 5.8 events laravel 5.8 feature laravel 5.8 features laravel 5.8 global middleware laravel 5.8 install laravel 5.8 lazy loading laravel 5.8 listeners laravel 5.8 middleware laravel 5.8 multi auth laravel 5.8 named resource routes laravel 5.8 named routes laravel 5.8 new feature laravel 5.8 own artisan command laravel 5.8 queue laravel 5.8 queues laravel 5.8 routing laravel 5.8 telescope laravel 5.8 tutorial laravel 5.8 user auth laravel 5.8 user authentication laravel 5.8 what's new laravel 5.9 laravel admin permissions laravel api laravel artisan command laravel artisan console laravel assets laravel auth laravel auth role laravel authentication laravel authorization laravel axios post example laravel background process laravel background task laravel background worker laravel beginner to master laravel belongsto laravel belongsto vs hasone laravel belongstomany laravel best packages laravel best practices laravel best tutorial laravel bootstrap laravel command laravel command line laravel commands tutorial laravel composer install laravel connect db laravel console command laravel console testing laravel contact form send email laravel controllers laravel create laravel crud laravel crud policy laravel custom command laravel custom middleware laravel database laravel database configuration laravel database relationships laravel database seeder laravel database settings laravel db seed laravel db settings laravel debugging laravel deploy aws laravel deploy digital ocean laravel deploy on digitalocean laravel deploy on server laravel deploy to production laravel deployment laravel digitalocean laravel drag and drop file upload laravel dropzone file upload laravel dropzone image upload laravel e-commerce laravel eager loading laravel eager loading tutorial laravel eager loading with condition laravel elixir laravel eloquent laravel eloquent belongsto laravel eloquent crud laravel eloquent hasmany laravel eloquent where laravel eloquest tutorial laravel events and queue laravel events tutorial laravel factory laravel feature test laravel feature testing laravel fetching data from database laravel file storage laravel fillable example laravel flash message notification laravel for beginners laravel form validation laravel forms laravel forms bootstrap snippets laravel from scratch laravel from the ground up laravel front end laravel frontend tutorial laravel gate and policy tutorial laravel global middleware laravel hasmany laravel hasone laravel i18n laravel installation laravel installation mac laravel intervention image tutorial laravel javascript tutorial laravel jobs queue laravel language laravel language switcher laravel language tutorial laravel languages laravel lazy loading laravel listener event laravel listeners laravel localization laravel login laravel mailable tutorial laravel many to many relationship example laravel markdown email laravel markdown mail laravel mass assignment laravel middleware laravel migrate fresh laravel mix laravel mix 5.8 laravel mix vue laravel model factory tutorial laravel multiple language laravel mysql json laravel named resource routes laravel named routes laravel new features laravel news laravel nginx laravel node modules laravel npm install laravel npm run watch error laravel one to one laravel paginate laravel paginate link laravel pagination laravel pagination 5.8 laravel pagination links laravel pagination tutorial laravel phpunit laravel phpunit testing laravel pivot table example laravel policy laravel preview laravel query optimization laravel queue laravel queue event listener laravel react laravel register user laravel registration laravel registration validation laravel relationships laravel reset password laravel role middleware laravel role permission laravel roles laravel route group middleware laravel routes laravel routing laravel routing with parameters laravel sass laravel save file to database laravel scopes laravel seo tutorial laravel server laravel session data laravel ssl laravel supervisor laravel tailwind css laravel tailwind setup laravel tdd laravel tdd tutorial laravel telescope laravel telescope installation laravel telescope tutorial laravel test driven development laravel test workflow laravel testing laravel testing controllers laravel testing tutorial laravel tools laravel translation laravel tutorial laravel tutorial for beginners laravel ubuntu server laravel ubuntu tutorial laravel unit testing controllers laravel upload file laravel upload image to storage laravel upload multiple files at once laravel upload multiple image to database laravel upload multiple images laravel url slug laravel vue laravel vue js crud laravel vue setup laravel vue tutorial laravel vue.js laravel webpack error laravel webpack tutorial lazy loading lazy loading laravel lazy loading vs eager loading learn laravel learn laravel framework step by step localization in laravel localization laravel many to many laravel mvc tutorial for beginners in php mvc tutorial laravel mysql mysql relational database mysql relationship n + 1 problem n + 1 problem laravel new artisan command npm install npm run dev npm run watch laravel one to many one to one one to one laravel own artisan command pagination pagination bootstrap pagination bootstrap php mysql pagination laravel pagination laravel bootstrap pagination links pagination php php php artisan php carbon immutable php framework php framework 2019 php what's new 2019 phpunit phpunit laravel phpunit testing pivot laravel policy laravel polymorphic relationships queue and events queue email queue for laravel queue jobs queue laravel 5.8 registration form relationship laravel eloquent relationship mysql restful controller role permission in laravel roles laravel route model binding laravel routing in laravel save image to database seo friendly seo friendly content writing seo friendly website seo laravel seo optimization simple pagination laravel slugify sqlite relational database sqlite relationships between tables symfony command console symfony laravel tailwind css tailwind laravel mix telescope laravel tutorial laravel unit testing unit testing laravel upload file laravel upload file php upload image laravel upload image to database php upload images laravel upload multiple files in php url slug laravel url slug php vue vue.js vuejs laravel why use laravel queue why use queue