Laravel 5.8 – From The Ground Up - Laravel 5.8 Tutorial From Scratch – e47 – Eloquent Relationships Many To Many (BelongsToMany)

Education, Programming

Laravel 5.8 – From The Ground Up

52 Lessons

Laravel 5.8 Tutorial From Scratch – e47 – Eloquent Relationships Many To Many (BelongsToMany)

we're gonna be tackling a many-to-many relationship between two tables and the example that we're gonna be working on is we're gonna continue to work with our

user model and user table but now we're gonna add a new independent table for roles and typically in an application you're gonna have a set number of roles that a user could be attached to or

detach to as they gain or lose permissions in your application we're not gonna be tackling that part of the application but we're gonna be tackling the database and the relationships

necessary to make something like that work so first and foremost like I said we're gonna be using our user model and our user model ships with laravel so we don't have to touch that for now let's

make a new model for our roles jump to the terminal and let's say PHP artisan make me a model with a migration and we're gonna call it role obviously singular we've covered all of this let's

jump back to PHP storm and let's modify the migration create roles table we're gonna be keeping this very simple we're just gonna say as a string will have inning and that's it nothing else in a

many-to-many relationship you actually have two totally independent tables that are not related to one another there is a third table which is what's called a pivot table that connects them

however as you see here in this roles we're not gonna add a user ID and the same way we're not gonna go to the users table and add a role ID there's no necessity for that because we're gonna

actually make a third table so let's make that now we've never really done this before but let me run PHP artisan you can actually just make a migration we look here we have this makes

migration so let's do that now PHP artisan make migration so what are we gonna call this pivot table now in levo the convention for this is that we have a role and we have a user so that is

exactly it we want to keep them in alphabetical order so role of course are comes before you and we're gonna keep them singular so it's not roles users but it's rather row singular user so

that's what we're going to call our table user altogether so what are we gonna name the migration we're gonna say create the role user table and then we

can pass it in the create flag and say we're gonna create the role user table so the role user table is what's going to put together our two other tables our user and our role table so let's run

that now now this is not gonna create a model for us this is simply creating a migration so let's take a look at that now create role user table perfect so this table only needs two things will

say table you're gonna need an unsigned big integer for the role ID and we're gonna need another one for the user ID makes sense right so each one is gonna need to have a reference to a role and a

reference to an ID and that's it let's leave the timestamps for now these are optional but sometimes in your projects you're gonna want to know when you granted that user that particular

permission that's where the timestamps will come in handy however out of the box they're not gonna work but I'll show you how to make those work all right so let's jump back to the terminal

PHP artisan migrate to apply those changes and if we jump to the table plus hit refresh so now we have our roles table and we have this role and user so very quickly in my roles table I'm just

gonna add just a random role I'm gonna say maybe it could delete a user it could be one row and another one could be that it could add a user right so we'll say that those are the two roles

that our application can do it can delete a user and it can add a user perfect all right so I'm gonna hit save head back to phpstorm and here we are alright so let me close

all this up let's move over to our routes file and let's do something here so let's say that we have the following first of all we need to create a user because we don't have one so let's take

care of that first and foremost app user class will say create me that class and if I jump back to Chrome and just hit refresh now we should have a user in our table and let's check this out users and

sure enough we have this user with ID of one so that way we don't have to create any more users from here now all right so back to phpstorm so now that we have a user we can fetch our user

saying go ahead and grab the app user first just give me the first user in the database so now we have that user and now let's grab some rules let's grab all the rules how about that so rules are

gonna be app roles oh and this will return a collection of all of our roles let me die and dump that so you can see what we have back to Chrome and sure enough we have a collection with two

items in it and each one will be obviously our delete user role and we're gonna have a second one which is going to be the add user role so how do we attach this that's just it let's set up

that relationship that's what we've been working towards in all of this setup so let's go to the user model and right down here we'll add a new method called roles and what do we do here well we're

gonna return this it belongs to many so it belongs to many ro+ and the same exact thing if we jump to the role let's go ahead and say well this belongs to many users okay so we'll

have users will say returned this belongs to many user class so now we have this relationship that we can use to attach them so let's do that now now that we have our user let's say user

roles we're gonna use that relationship and then we're gonna say attach the rules and that's it that's all you have to do now before I run this let me jump back to table plus and I want to show

you that our role user table is completely empty right there's nothing there back to Chrome now that we've set up those relationships I'm gonna hit refresh and now let's go back to table

plus hit refresh and now here we go so we have a user with the idea of one is attached to a role of one and then the same thing user ID of one has a role of ID too so we've successfully attached

those two things together great so of course this is the way that you attach and associate models to one another so similarly of course you can detach models using the detached keyboard so

while I'll actually do is let's detach the first row from our user well you detach method again to give you a before-and-after

here's table plus before we have two entries in our database and remember the updated and created are are still not working I'll show you how to do that now so then let's jump back to Chrome now

that we've made the change in our code I'll hit refresh back to table plus hit refresh and there we go so we've detached the first row of our user so that's the easy way in and out let's

make the timestamps work now let's jump to phpstorm and in our relationship all we have to do is add another method call and say with timestamps and then let's do the same thing in roles

we'll say with timestamps this lets letter well know that we do want timestamps in our pivot table hit save and back here let's go ahead and attach that role one more time and here's the

before refresh all right let's run the code let's head back refresh and there we go so that is attached again but this time of course we do have it created at and updated at let me do something else

let's add some more roles to our application how about this modify user delete comments and let's add maybe one more edit comments comments there we go all right so now we have all of these

different roles so most of the time a user is gonna have an array of roles that you want them to have so let's say in the case of our application I want our user to be able to do maybe one

three and five that's it just one three and five those are the roles that I want my user to have so a lot of times while you actually do is instead of having roles we're gonna have IDs so we can

actually pass in an array here of IDs so we'll say ID 1 ID 3 and ID 5 referring to the IDS of our roles so a user can have IDs 1 3 & 5 from our roles table alright let me go ahead and save that

again let me show you a before and after here is our roles user table currently let's run the code refresh looks like there was an error but errors at the die and dump because we no

longer have rules but it should have still worked so let's head back the table plus hit refresh and sure enough we have ID 1 ID 3 and ID 5 were attached to our user but we notice a problem

right away and the problem is that all of a sudden our user has a duplicate there's nothing constraining in the database that wouldn't allow a user to gain the same permission multiple times

so typically this is not the way that you would do it the way that you would actually do it is using another awesome method that lenovo has and that is the method sync so let's jump back to

phpstorm and let's change that now so instead of attached let's use sync sync will sync up any roles that that user has to only be 1 3 & 5 so let's do that now let me get rid of this dying dump so

it doesn't error out on us hit safe let me give you there before again hit refresh so this is what we have right now right notice there's 5 entries in this table then let's jump to Chrome to

run that code hit refresh back to table plus refresh and there we are so this user now has 1 3 & 5 however we still have this duplicate here of one let me actually delete everything out of this

table just to show you that it does work hit refresh go back refresh and there we are 1 3 & 5 so let's change something else in our code to see what happens let's go back

to phpstorm instead of 1 3 & 5 I'm gonna say 2 & 4 these are the two roles that I want attached to this user all right let's go back to Chrome refresh back the table plus refresh and sure enough we

only have 2 & 4 1 3 & 5 disappeared so that is an awesome methan gonna use that all the time there's another method that you might use sometimes as well and that is the sink without detach

sometimes you may just want to add a role to a user you may not want to delete everything and start from scratch like for example if all of a sudden this user should be able to let's say modify

a user that's ID 3 we should just be able to tell their bow hey go ahead and add the ID of 3 but do not detach anything go ahead and keep all of the other

permissions the way that it should be just give them the ability to modify a user and that's what the sink without detach does for us let's check that out phpstorm like I said I want to give them

ID of 3 and let's say sink without detach let's hit save back to Chrome hit refresh looks like we get an error sink without detach oh I know what it is sink without detaching detaching not detach

all right let's run that again so that runs perfectly so let's go to table plus and look at our roles and users and there we are so now that user has role 2 & 4 which was the original but now we've

added 3 which was the role that we added notice that in this scenario we only passed in a role of 3 that's the only thing that we passed to that we've been doing all of this starting from the user

but of course we could flip this and start from the role as well and it would work exactly the same thing so let's do an example of that very quickly let's say I'm just gonna comment this out and

let's grab a role and our role is gonna be let's just say give me the role find ID of 4 ok and then we can say role users and then I'm just gonna use the sink method and I'm just gonna say just

user 1 that's all I want you to attach to that role all right now notice that a did import role up here at the top but of course if you have any issues with role you can do the full name space like

so so we'll change that it'll be exactly the same thing let's jump back to Chrome hit refresh and back to table + hit refresh of course role ID 4 is already attached

to user 1 let's do another one so that it does actually change let's do role ID of 5 all right so 5 is not currently here 5 is not there let's say 1 change that to 5 there we go I

think now we're gonna see a difference refresh back the table plus refresh and there we go so 5 perfect so we have user ID 5 has a roll of four that makes total

sense that's what we wanted to do so obviously this relationship can go either direction now in a more advanced topic we can add additional fields in this pivot table so in the next episode

we're gonna be covering how to actually add additional fields to the pivot table so that way you can store data that is related to the fact that two things belong together so start to implement

this in your application and when you're ready let's move on to the next episode

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

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