Laravel 5.8 – From The Ground Up - Laravel 5.8 Tutorial From Scratch – e46 – Eloquent Relationships One To Many (hasMany, BelongsTo)

Education, Programming

Laravel 5.8 – From The Ground Up

52 Lessons

Laravel 5.8 Tutorial From Scratch – e46 – Eloquent Relationships One To Many (hasMany, BelongsTo)

let's take a look at a one-to-many relationship in laravel this is probably the most common of the relationships and it basically states that there is one

owner and that owner has many of the secondary property and what I mean by that is the example we're gonna be working on today today we're gonna be working on a user has many posts so a

user can have an unlimited amount of posts but a post belongs to a user so I have a fresh level installation here so let's start working from scratch let's make a new model PHP artisan make model

for a post and go ahead and give me a migration for that there we go we're gonna keep this very simple for the example let's go to the post and let's just set guard it to an empty array that

way we disable mass assignment and let's go to the create post table and let's just keep it very simple this table is gonna have a string for a title in just a text for a body and of course as

always it's gonna need an unsigned big integer for a user ID because of course each post belongs to a user so we need that here to reference the user ID now we are going to be using labels user

table that it comes with without changing anything at all alright so we have that we have that now let's go ahead and migrate our database so PHP artisan migrate and there we go alright

so that is ready to go for us so let's set up these relationships let me pull up the post model and let's add a new public function for user so remember a post has one user so return this belongs

to app user class perfect now we need to go to the user and do the same thing so let's go over here to user and at the bottom let's add a new public function for posts notice that this is plural not

singular because remember a user has many posts so it needs the plural posts and in here we'll say return the has many what does it have many of well it has many a post and that's it our

relationship is good to go from there on out so a user has many posts and a post belongs to a user perfect so let's jump into the web routes just to have a quick playground here and let's whip up a post

so we can say our post is going to equal a new app post and we want our post to have of course we know it needs a title title here and we know that it needs a body so we'll just say body here so at

this stage we have a post but we haven't saved it to the database let me die in dump but just so that you see what we have let's jump to the browser and there we are we have a post and we have two

things but notice that it is not persisted we need to persist it and so to persist it we actually need to make a user so let's make a user here at the top we'll

say our user equals let's use our factory and say give me an app user class create one of those forests so at this stage you could do several things right so the long form of this is that

we would actually pass in a user ID and we can say well the user ID is gonna be the user ID that makes sense and then we can call post safe so this is obviously the long form let's see

what happens hit refresh it says that the body was not found let's check out what happened create post table ah I misspelled that body not bad

alright perfect let's try it again PHP artisan migrate fresh there we go let's try there again there we go now it's working so we can tell that it's saved because we actually have an ID but

we're having to pass in a user ID so let's jump back to the PHP storm and let's check out the short form of this so we can get rid of this altogether what we could do is use the relationship

on our user model so that would look something like user and then we're going to call that posts and then we're gonna say create and to this create method is what we're

going to pass in this array right here so let's cut that out let's put it in here and now we no longer need any of that and then we can simply say grab the user and give me their posts that way we

get all the posts together and if we hit refresh we have another one so there we go so that is working exactly the same way you see that the user ID is being set for us even though we are not

actually telling laravel how to do that so that's pretty cool so we have that now but what about updating how do we update this post well there's several ways that you can do that for example

what if I want to take my post and then I'm gonna say give me the first one that way I have a post instance and then I want to override the title let me actually jump this out of the Dynamo

so the title is gonna be new title but then I want to save all of that so we can actually say user push what that's gonna do is save the changes to our post but notice that I'm calling push on user

not on post let's see what happens now hit refresh actually we don't get anything we do need to die in dump let's die and dump something else actually know what let's return our user post

that will give us a JSON array refresh and sure enough we see that we have new title here so that's how you would update a relationship just to drive the point even further let's go ahead and

change the body as well new better body how about that so now we're gonna push those changes and then we're gonna fetch that let's see refresh so now we have new better body and new title so that's

how you would update the post through the user relationship now of course in the long form of this just to show you the difference I'm gonna get rid of that and I'm going to say alright so my post

is gonna be user post and then I could say post title equals new 1 2 3 and then we can change the body to body 1 2 3 and then of course I can call post save those changes for me all right let's try

that now I'm sorry user post this needs to be first that's gonna return a collection and then we have first all right let's try it again there we go

so we have new one two three and body one two three but of course that's not ideal because imagine that you had two or three different relationships and you're trying to save everything at the

same time so of course the nicer way of doing this let me return back to what we had before is to do it this way you're going to make all of your changes and then on your parent model you're gonna

call the push and push will automatically push all of those changes over into the relationship without you having to go in individually and do one at a time so there we go that is a

one-to-many relationship in level now there are a couple of more methods that you can call like save many or create many that will help you create several posts in one single shot so I suggest

you go check out the one-to-many relationship in the documentation if you're in need of something like that but for now this will cover the basics of a one-to-many relationship in laravel

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

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

Code for this Lesson
https://github.com/coderstape/laravel-relationships/compare/one-to-many

DigitalOcean Referral
https://m.do.co/c/7dce5364ef4d

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