Laravel 5.8 – From The Ground Up - Laravel 5.8 Tutorial From Scratch – e14 – Eloquent BelongsTo & HasMany Relationships

Education, Programming

Laravel 5.8 – From The Ground Up

52 Lessons

Laravel 5.8 Tutorial From Scratch – e14 – Eloquent BelongsTo & HasMany Relationships

welcome back in this lesson we're going to be looking to associate our customers with a company and the first part of this is gonna be a bit of a review we're

gonna create a model and a controller and then we're gonna get to the actual meat of this lesson which is eloquent relationships so stick around and you'll see how easy it is to have relationships

with laravel and eloquent the first thing we're going to do is we're going to go to our console and we need to generate a model so we'll say PHP artisan make model and

what's the model gonna be called remember our models are a singular version of what we are going to do so we're gonna have companies but our model is gonna be company so company and if we

need the migration to go with it we're gonna add the – M flag so there we go so we've created a model and we've created a migration so back in phpstorm let's start with our migration so it's

gonna be called creates companies table and so let's keep it simple I'm gonna add a string for name and that would be company name and maybe let's just add one more for phone just to keep it very

simple we're gonna do just a name and if phone let's go ahead and hit save so let's take a look at our company model and it's going to be called company and that's inside our app directory just so

we keep track of this inside our app directory here this company as I've mentioned before I almost exclusively always have my mass assignment protection turned off so I'm gonna do

that now protect it guarded equals empty array and if you're unsure about mass assignment check out the previous lesson where we go into in-depth between setting fillable fields or setting the

guarded property to an empty array so now that we have guarded off it is basically turned off completely up next I want to create a company so obviously right now I don't have a view for that

yet so the easiest way is to boot up PHP artisan tinker and let's whip up a new company so C equals company and of course we can use this notation because we added our garden equal to

empty array otherwise remember this will give you a mass assignment error so now we can say name just ABC company and we'll have a phone all right those are the two fields that we had added so

phone one two three one two three one two three four all right so now we have a company in our database so so far this is all review right we've done all of this before so hopefully it's starting

to feel a little bit better in terms of flow now here's the new part of this so this company is gonna have some customers right it's what we call customers so a customer to us has an

Associated company so the way to think of that is we can say a company has many customers and a customer belongs to a company and that's exactly how we're gonna write it so let's head back to

phpstorm now this is my company model and let me pop open my customer model I'll pop them open side-by-side so let's add a new relationship so this is how you do it in my company model right

remember a company has many customers so we'll add a new public function called customers and inside this method return this has many customers class this public function is called customers and

customers again is the plural of customer if you keep to this naming convention of singular to plural everything just works you can always override this if you don't want to

follow the convention but for now just to keep it simple just follow the convention so public function customers a company has many customers and then let's write the inverse in our customer

model public function company singular and we'll say return this customer belongs to a company and that's it just like that our customer is associated to a company and

our company is associated to a customer we have one last little thing that we need to take care of and that is the foreign key in our database in order for us to associate a customer to a company

that customer has to store a company ID so let's take a couple of step backs and take a look at our create customers table so far in this table we have the name the email and this active column

that we worked on a couple of episodes ago so we need to add a new entry here unsigned integer and it's gonna be company underscore ID so that's the convention we have a company model and

then on our customer we have to add a company underscore ID so this hit safe I know that I had already created a company and tinker we're gonna have to create that again so let's do PHP

artisan migrate and I'm just gonna call the fresh and fresh will give us a blank database all together but we do see here we have our customers table and we have our new company's table so let's create

a company now I'm gonna use PHP artisan tinker again PHP artisan tinker company creates and remember I can use the create method because I already set my guarded equal to empty array so we'll

quickly say name ABC company and the other field we had was just a phone and we'll say one two three one two three one two three four alright so create that company for me perfect in our form

in our customer form we need to add a drop-down so we can actually select the appropriate company for the customer that we are creating eventually of course we'll have to add a form to be

able to add companies but for now we'll keep it simple and do this this is not for active this is gonna be for company ID and we'll say company and so for our select here of course we're

gonna have to pass this data to our view so let's go to the custom our controller and let's see what we need to do here so our list is currently getting a list of active customers and a

list of inactive customers so we're gonna need a list of companies and we'll do that simply by calling the all method on it we can always scope this down to active companies and stuff like that

again we're keeping everything as simple as possible let's go ahead and pass that into our compact so let's use the blade syntax for each for each companies as company and then end for each and what

we're going to have here of course is an option for each where the value is gonna be company ID and the name is gonna be company name alright let's check it out in the browser refresh and there we are

so obviously ABC company is the only company we have in our database right now so let's add a customer we'll say John Doe John at example.com status active ABC company add customer and we

get an integrity constraint violation the reason why this happened is because remember we are validating specific fields we did not update that in our controller so let's take a look at that

now so right here we have name email active let's add a new one for a company ID and we do know that that is required all right let's hit refresh and there we are so we added this customer so check

this out I'm gonna boot up PHP artisan tinker one more time because I do want to show you this relationship so I'm gonna fetch my company and we're gonna fetch that by

saying company give me your first one so now we have company saved to this company alias so if I say company give me your customers there we are

so we've associated John Doe to this company right here and we can do the inverse of that so we can say customer let's fetch the first customer and let's say customer give me your

company so we are able to associate a company to a customer so I want to use that relationship right now to reflect that in our customer view so we were using the email but what I

actually want to do is instead of the email I'm gonna fetch the company relationship so we'll say active customers company and give me their name so again active

customer is fetching the company relationship which we established in our customer model let me show you that now right here but notice that we are calling it without using parentheses

right we are not calling company parentheses it's company as a property and we'll take a look at the difference between calling it as a property or calling it as a method but for now just

remember no parentheses so active customers company and give me the company's name is it safe and let's check out what we get so we are able to get that ABC company right into here

that's pretty cool so in my view I actually want to add one more little section and it's just to prove that we can fetch the relationship in the other direction so let me add a

row and for now we'll just keep it as a column of 12 inside and here let's just do for each company's last company and for each let's output the company's name in the h3 tag so company name and then I

want to fetch all of the company's users we'll keep it simple and keep going with this there's a better way of doing this but for now we'll just say for each company customers and that's gonna give

us a collection as customer we'll wrap this in an unordered list really quick here but list item customer and give me their name and then and for each let's wrap this whole thing in an unordered

list there we go all right let's check out what we have now so right now ABC company has one customer John Doe and the way we fetched that relationship was by calling company

and then fetching all of their customers and then we're iterating through each of those customers as customer and outputting that to an unordered list and then we have at the

top we are using it to fetch the company's name so let's check that out so right up here we have our active customer we're fetching their company and fetching the name of the company

again the relationship for that came from our model in this case this is the customer model we have this company relationship here established and in our company model we have a customer

relationship here established in our migration for our customer we did add a company ID which is obviously a foreign ID for the customers table and this is what represents our company and then

from there now everything just works I'm gonna add one more company and add a new customer to it so you can see it all working in the browser so let's add the first company first I don't have a view

for that so I'm gonna have to revert back to adding it through here let me go up a couple of clicks here so we'll have a new company and this company is gonna be called the EF company now let's go

back to the browser I'm gonna hit refresh and so now we have the ABC company and we have the d EF company let's add Jane Doe to the list and Jane is Jane and at another test com we'll

make her inactive it won't make a big difference we'll hit add customer and there we are so we have Jane Doe associated with d EF company John Doe is associated with ABC

company and we are able to fetch all of the customers for each of these companies to prove that I'm gonna add a third person here and we'll call them John Smith John an example is fine add

customer so that we are John Smith and John Doe both belong to ABC company as we see it here and Jane Doe belongs to D EF company as you see it here so the has many and belongs to relationships

are probably one of the two most used of the eloquent relationships but we're going to continue to work on relationships throughout this series and we're going to dive deeper through all

of them just like we did with these two so keep playing around with these relationships and adding more tables and trying to associate them and when you're ready we'll move on to the next lesson

In this episode, we are starting out by reviewing what we have learned so far to create a company model and migration. For new content, we are tackling connecting the company to a customer using the belongsTo and hasMany eloquent relationship.

For the best experience, follow along in our interactive school at https://www.coderstape.com

Resources
Course Source Code
https://github.com/coderstape/laravel-58-from-scratch

Hit us up on Twitter with any questions or comments @codertape (https://twitter.com/CodersTape)

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