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

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
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
Info
Channel: Coder's Tape
Views: 32,062
Rating: undefined out of 5
Keywords: laravel many to many relationship example, laravel belongstomany, laravel pivot table example, many to many laravel, pivot laravel, relationship laravel eloquent, mysql relationship, hasone relationship in laravel, one to one laravel, laravel one to one, eloquent, belongsto, database relationship, laravel database relationships, mysql relational database, relationship mysql, hasmany laravel example, laravel belongsto vs hasone, laravel eloquest tutorial, laravel 5.8, php, mysql
Id: f7quw05phxs
Channel Id: undefined
Length: 13min 54sec (834 seconds)
Published: Wed Apr 17 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.