Laravel Advanced - Has One Relationship

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what's up guys welcome to lighters in our previous videos we have discussed about eloquent model so in this video we'll be talking about eloquent relationship most of the time in a real life project two tables or more than two tables are related to each other let's say a post can have many comments a product can have many reviews a user can have one profile so in this way they are linked to each other so there are a lot of way we can define the relationship so there can be one to one one too many many too many you can see a bunch of list over here but in today's video we'll be talking about one-to-one relationship let's say there is a users table and there is profiles table and a user can have only one profile and he or she cannot have more than one profile then we can give define a relationship between them using one to one relationship because one user can have only one profile so let's get into it by default we have users model in our larval application so we'll be using that and we'll be creating a new profile so which i have already created i'll be showing you here so here is a profile model and here here is a profiles table so which will be related to the user's table by using a foreign key which we have already seen this in our migrations video so here i have defined a foreign key as a users table so it is we can relate this table profiles tables with users table then it has a bunch of other fields like phone city postcode and country i have made these nullables so that i could show you one more example in the relationship then in the users table that we have all everything that we get with the laravel and this is admin field this one we added in our previous video so we have these two tables and also i have seeded some data here there are 10 users and each user have a profile so you can see here user 1 to 10 we have a user id here and the user's id here also we have 1 to 10 so each user has one profile so these data are already seated okay now i'll show you how to define a relationship okay here if we go to the users model and here we can define a relationship like this we can give it a name as profile and we can return a relationship from here so we can return a relationship like this this has one profile because a user has one profile so it has the syntax as a human readable so we can easily understand that by seeing this method that a user has only one profile okay now if we define it like this so by default laravel follows a convention if we define here a profile then it will look into the profiles table in the plural form so we have that here the profiles table yeah and the second parameter we can give it here as a foreign key which is the foreign key in the profiles table so in the profiles table we have foreign key as a user id and if we don't provide here any foreign key the laravel will look at this table this modal table since you there is a user and the table name is users it will by default consider the second parameter the foreign key as user underscore id the singular user so if we have any other column name rather than the foreign key as the id as the user id suppose let's say we have here as the author id then for that we have to run right here author underscore id otherwise it will not work so since we are following the convention so we don't have to write anything here but if we want to write then we can write here user underscore id it will work the same way writing the user id here and not writing here will work the same way because we are following the convention because we are making a column in the profiles table which has a user underscore id so in this way we can define a has one relationship in the users model if we do this then we can access this profile okay so let me go here in the tinker well and let us find a user user find with an id of one if we do this then we'll get the user with the id of one which is here in the database and if we look here in the profiles table the user id for the user id1 this is the profile the data related to the profile is here so how to access that relationship so since it is returning a relationship we can access this relation as a simple property of the model let's see now if we want to access the profile then we can simply say profile profile here and if i reload here then you can get all the data of the profile now now you can see here it is returning a model's profile and here you can see here the country name is ireland and you can see here the country name is ireland let's say we for the user id of the five let's say we want to see its profile then we do like this then we can see here the country name is marshall island then here also we can see the country name is marshall island so in this way we can access our relationship has one relationship from the model now we have defined a relationship user has one profile but a profile also belongs to a user since a user has one profile so user so the profile belongs to a user so now we can also define a relationship in the profile so if we go to the profile then we can define a relationship like this so it's a belongs to relationship so we can give it since a profile belongs to a user we can give the name method name as a user and return a relationship so this relationship has to be must be this belongs to a user okay so here also there is one convention so this we are writing here user yeah in the profile let's go to the profiles table here so there is a user id so if we write the name as a user then it will take this second parameter as user underscore yeah so by default we already have this user id in the column and we want that to be the case so we don't have to write anything again let's say we have author id here then we have to pass here author underscore id then only it will give us the relationship so now if i go to the profile let's say now i'm accessing profile model let's say i'm finding the third one yeah if i reload here it will give me the profile model here now if we go here in the profile and here in the third the third id of the profile is related to the user with the id 3 and if i go here the id 3 is this and to access this also we have similar syntax so we can do user here like this so you can see here we are getting a user model and it is returning the same message to one so if we see here in the database so you can see here the use the name of the user is user here and here is same so let's say now if we give it a name as author yeah now to access this so we are in a profile model yeah here is author method belongs to relationship and if we go here and if we give it here author name now if i return here it will return null because the laravel will think that in the profiles table there is author underscore id column and it will try to access the author from there but in here we have user underscore id so we have to define here the column name so which is user underscore id so if we want to give any other name other than user to the method name then we have to define the foreign key here if we do it like this then if we go here and reload now you can see here we can get the user of the related profile okay this is how you access relationship from a single model now let's see how to access the data from multiple models okay let's say i'm getting all the user data so if i do it like this then i can get all the user models so that currently there are 10 models so i am getting all the 10 models so as you can see here all 10 models are shown now to load the relationship here what we can do is so let me show you this using the browser and i will also show you some problems with it and how to fix that problem so if i am here in the home page and let me go to the web.psp here in the home page in the home controller inside the index method and let us get all the let's see users here we can pass it directly here like this user gate and we can loop into the users and store their name here let's see the mt4 yeah this is some some tailwind classes so what we can do is we can loop into the user since we have passed the users here so we can loop into that and show the users for it users as user and we can so some user here okay border bottom okay now we can see here we have 10 users yeah and if we see here in the debug bar here and below so only one query has been drawn now let us try to access the profile okay now from the profile what we want is we want to show the users city and the country name so what we can do is we can do so we have a user model now to access the profile from the user we have already seen before so we can just access it as a normal property so it will return a profile model the profile of that user and now we can access the property of the profile so here in the database we have city and we can also access country so for now let us let us only try the city okay so if we go in the browser and we refresh the page here now you can see here we are seeing the city for all the users yeah now here if we go in the queries so it is running now 11 queries which is creating n plus one problem so n plus one means basically there are ten users and each user has a profile so if we loop through it then it will take so this one query is this one from the n plus one one means this query which is getting all the users yeah this and the n means total number of profiles for each user yeah so to get the profiles of each user we are creating one request per user so there are n users so we need to perform n number of queries to get the profiles so it is saying n plus one so because of that it is said as n plus one so we are getting n plus one queries so the beginners will not realize this which since they will not know about the tools like this debug bar and they will not know how many queries is being run and it will if the number of the users or the let's say these are the number of products that we are showing in a website then it will hit the performance of the website so now there is a solution for this as well in the level so let's see how to solve this we can solve this by using eager loading now if i go in the tinker well now to either load what we can do is we can pass with here yeah okay i'll show you this in the documentation as well if we go into in the eloquent relationship in the eloquent quran on the relationship if we go here in the eager loading now you can see here we can load the relationship like this so we have a relationship name as profile so in this case the relationship name is author so here laravel is writing here in the documentation there is author but we have a relationship name as profile so we have to write profile here so if i do here like this and pass profile now you can see here we are getting only users yeah but if i execute this then you can see here we have we are getting this extra profile information so we will also get the profile along with the users now let's see what query is run by the laravel when we execute this so now let's go into the home controller and run this as well with so we can access the we can write the syntax like this or we can also write the syntax like this yeah so we have multiple relationship then we can pass it like this yeah so just be consistent with it either pass it as a parameters or pass it as an array so let us be consistent and only pass it as an array so passing the multiple parameters seems more relevant with the arrays so i'll be using arrays here so if you want to pass it as a parameter then just be consistent and use like that in every part of your project so that it will be easier to debug okay now let's see what happens so we have just added with profile here yeah so it is now it will now igor load the profile now if i go now you can see here it is running this 11 queries yeah now if i hit refresh here now look here the queries has been reduced to 2 only so it is getting the users all the users yeah and is applying those ids in the profiles and getting the profiles of those users so it is basically performing where in in the mysql yeah it is getting all the users and performing getting all the profiles where in the user id is those all that got from here so basically we will only get the two queries here so laravel is not performing any kind of join yeah or inner join or crosswind it is not performing anything it is just getting the users and grabbing those ids and and getting the profiles for each users so these queries will run and our performance will be increased so let's say in the home page basically for an e-commerce website will be showing lots of products in the home area there can be lots of categories lots of products lots of sections in the homepage so which will be showing lots of product products and in each product if we grab let's say gateway we want to show the categories of this product then there will come the issue of this n plus one problem everywhere so which will cause your application to be slow so if we use the eager loading then our application will be very fast so if we if you see a lot of data in that in this users and profiles table and see here the execution time and the ram uses then if you eager load then it will be really low and if you don't igor load then it will take a lot of time to load this page and now we have seen how to define a relationship and inverse relationship inverse means belongs to relationship and we have seen a lazy loading also let me show you we can do this in another way as well let's say in some cases you have you already have the users models yeah you have already received the user models and in that case also you can pass a parameter by which you can load the relationship so this is known as lazy loading so previously what we did is known as eager routing yeah now this is known as lazy loading since we are loading after getting the data so what we can do is load and give the relationship name as profile here and if i go in the browser refresh it then you will see we are getting the same queries and if i show you here in the tinker well as well if i go here get and if i do here load and if i say profile and reload here you can see here the result is same so we can eager load as well as we can lazy load we have seen that now let's see how to check whether a relationship exists in a model or not so let's go to the documentation for that i'll show you where it is so if i go here in the documentation and you can see here querying relationship and here we can see here all these things laravel has in the documentation now here is the querying relationship existence so there is has method in the modal instance which we can use to check whether a relationship exists in a model or not okay let's see this in action using tinker well now here in our database for each user for each user there is a relationship here and let's see whether the results will be the same or not okay now if we do here has profile so if we do it like this so user has profile gate then it will get all the users that have profiled with them so if the user that don't have a profile then it will not get the results so for this so if we return it here now we will get all those 10 results so just to check here i do count here so this count method that we have learned in our collection video so if we do it then it will give us the total results that we have got so we have 10 users here yeah yeah that's true because we have all the users having the profile so now let us remove these 2 9 and 10 okay here now i have removed these profiles the profiles so now the user with one two eight id have a profile and nine and ten do not have any profile now if i go here and let me return the count here so now it should return it now if i reload here now you can see here we are getting it now if i remove the count and if i reload here now you can see here ids you can check the ids so one two three four five six seven and eight ids are shown and nine and eight users are not shown so have a look we have the return model is users model and it is returning a collection of users model so that we could perform all those eloquent collection methods on it and which are really handy so here we can get all the users that have a profile now there is also another method which will check the absence of the relationship by using that method we can get all the users that don't have profiles so we say doesn't doesn't have so user doesn't have a profile get those users now if i refresh here now you see we'll be getting those users yeah nine and ten id that we of those users we deleted profile so those will be available here so as i said previously i intentionally made this nullable here so just to show you one thing here so okay so it is saying here doesn't have yeah okay let me make here let let me use has for this okay because it has a lot of data and if i show you in the database for all these eight users now we can see here there are three fields that are null yeah and other all fields are not null now we can also get the results by this yeah so we we want to get all the users that have filled this postal code and we don't want to get all the others users now we can do it like this so here user has profile and here we can pass a second parameter function and it will get a query builder and here we can perform the eloquent query builder method so let's say query where so it will perform a query in the profiles table okay not in the users table but in the profiles table so we want to get only those users that have filled their postal code so p o s t post code so if postcode so there is a handy yellow point model method for this where square not null which will check whether this postcode is null or not so it will only return those that having a postcode that is not null okay now if i refresh here so it is saying expects parameter 1 to be string so this is not a has we have to so we have to use where has method for this where has yeah it will get the users where it has a profile where having a postal code only that so if i refresh here now you will see here it is getting all the users that have a profile whose which have the postal code field feed filled in and we if we see here the total number of users is one two three four five yeah and those ideas one two three five seven and if we see here ids of the user this is one yeah we can see here one and this two this three is also filled and this five is filled and this seven is filled so it is returning those and it is not returning this those have the null now we can so let's say we only want to show the users who haven't entered their poster code then what we can do is we're no and if i refresh here you can see here so these four users don't have this postcode filled in then so those users have the idea of four six and eight and you can see here four six and eight it has returned these users who haven't the postal code data field so like this you can perform the where has in the relationship so there is also where it doesn't have a method here but we can use that in the other relationship so in one to one relationship the user can have only one profile so that method is not relevant here so we'll be using that method in our one-to-many relationship in our future video okay we have seen here how to define a relationship and checking the existence of the relationship and reloading eagle loading the relationship and minimizing the n plus one problem now let's see how can we store data using the relationship yeah so before that before that let me show you something so we have deleted two profiles from here now if i go in the browser and refresh the base it should give us or some error okay let me show you here yeah you can see here trying to get the property city of non-object so trying to get the property of something this is the most common problem that many people or many beginners face yeah even the the developers have worked for several years they will also face this issue because this is very common in level so this is happening because i'll show you here because we are looping through all the users yeah all the 10 users now if we come here so if all the all the 1 to 8 users all the users with the id from 1 to 8 have profile and 9 and 10 do not have any profiles yeah for up to eight it will work fine and when it comes to the user with the nine id it will try to access the profile and it will return null here okay if i show you here user with profile and get here now if we see here yeah you can see here the profile is null yeah and if we try to get a property from here then it is saying trying to get the property of non-object since profile is not which is not an object so here we are trying to access the city from a null so it is saying that we are trying to access a property from or not from a non-object field so which is valid error so to fix this issue we can do multiple things so there is an optional helper in laravel we can use it like this optional so if we wrap anything within the optional and we access any property from here it will always return null yeah so this is one way of doing it so if we write any name so we give it any name ct or anything or any method here yeah it will always return null so let us try city here for now and if i go to the browser and refresh the page here let me minimize this and you can see here it is not giving us any error and here it is not giving a city so in the all of them above our are of three lines and these two are only of the two lines because they don't have city so this way we can work so and for the psp seven and or above i think we have null collision operator so which is double question mark yeah so what we can do is do it like this or let's say no so we can give it a default name like this so if it throws any error while trying to the x while trying to access the property then it will not throw the error it will fall back into this second part of this double question mark thing and it will display this basically what this does is in the two cases it will fall back to this case if anything in the left side is null then it will print this and if it throws any error or exception then it will fall back to this okay so in the in our case it is throwing an exception so it will fall back to this now if i go here and refresh the page now you can see here we are getting no city so we don't want to do any of these things then we can there is also another way of doing this so let me remove this and if we go to the relationship so we are accessing a profile relationship from the user so let's go to the user model and in the profile section so what we can do is here with default yeah we can pass this without any parameter if we pass here without any parameter then it will return a new profile if a user doesn't have any profile it will return a new profile object okay we have done it like this now let me go to a tinker well now you can see here in the above we have this profile model and there the data is filled in here and in these two the data is profile is null now we have passed with default now if i refresh here and go at the bottom now you will see here we are getting an object profile object and it is filling this user id since it is related to this user so this user id is filled in here so we are not getting a null we are getting a profile object profile model object and if we go here in the browser here and if we refresh the page so it will not throw us any error because if we try to access any property from the model and it doesn't have that property then it will always return null yeah so here we will not see any data here so let's say as in the previous case we want to show some default value those those users that don't have any profile or ct then what we can do is here we can pass the default values also so let's say we want to name the default city as city as let's say um london then now let me go to the tinkerbell first and if i refresh here and go at the bottom now you can see here it is passing the city as well here so in the profile we have multiple things like city postcode country all these fields can be passed here let's say for that let us pass country i don't know whether london is city or country okay let's say country as england yeah and if i go in the tinker well here and if i refresh here and you can see here it will pass the country as well now if i go in the browser here and if you refresh here now you will see here if the if the user doesn't have a city in a profile then it will by default so all london yeah by default you would show no city in the real scenario but in this i am showing you that you can pass anything there and it will be displayed here and also if we access the country from here then it will also give that country that we have passed in the default parameters okay so this these are the three ways how you can minimize that trying to get the property of non-object error okay we have deal with it now let's see how to save a profile from a user model using the relationship okay now here if we go into the tinker well let's do that from here as well let's say we have a user with an id of 9 line here and if i we can find it like this and user will be shown here since the user doesn't have a profile because we deleted now we can save a user so i will show you first by without using a relationship and then using a relationship yeah because we have already seen how to save a model save or data to a database using modal so we can use that way also so profile is equal to we can say new profile yeah and we can pass the parameters like this here in the database we can see here it's a user underscore id is equals to this nine dollar profile yeah we can do pass all the parameters like this and we can save since i have already shown this type of things in my previous videos so i'll be just be telling you how to perform this so we can save in a database like this yeah but now let's see how to store it using a relationship so with if we don't use a relationship then we have to pass the user id we know that we are creating a profile for a user but in this case what we have to do is we have to pass the user id as well but let's do it by using relationship now to do that what we can do is user profile here if we pass a method here so if we don't pass as if it as a method then we'll will get that default since we are getting this since we have added this in a default value yeah otherwise we would have got null so we will get a profile object like this and if i do it like this method then we will get here you can see here has one relationship instance yeah if we go in the users model now you can see here the profile we have we are returning the has one yeah so if we go it inside has one so you can see here it is returning this illuminate database eloquent relationship has one so we can see that in here yeah so this is basically the query builder this also extends the eloquent query builder now we are getting a builder instance now we can call here create like this and we can pass the parameters here yeah so but if we do it like this then user underscore id we should not pass that so it will by default be added by the laravel so we have to pass other fields except user id so if we go here in the database then we'll see here it's a phone now if we try to save it like this then we'll get exception that we have looked in our previous video which is mass assignment access then okay let's try this now you can see here it is giving us mass assignment exception because we haven't added these fields in the guarded sorry in the fillable property inside the profiles model since we are saving profile from here so it will look into the profiles model and the fillable property so it is not getting anything so it is throwing this error okay now let's go to the profile model here now we can define here protected filler world is equal so now we can give the name of all these pro phone city postcode and country yeah we can do that but there is another property that i forgot to mention in my previous video which is guarded so if we do here protected guarded and give it an empty value so it will disable the mass assignment yeah if we are very careful then we don't need need this mass assignment feature from the level here in this case we are passing only this specific data we are not passing like that we have seen in my previous video like request all we are not doing that we are passing the specific values so there is no any danger of any other data being filled in our database yeah only these columns will be filled any other field if there are any other fields then they will not be filled so there is no issue by issue if we disable this mass assignment and if we carefully save the data in the database yeah so now if i refresh here now you can see here it is returning the profile model means the data is saved now if we go here so you for the user id 9 there should be a profile inside the profile table so currently there is no profile for the user id 9 now if i refresh here now you can see here for the user id 9 the data is here and all those data are that we have entered here okay now if we access the profile from here now you can see here we can get that profile we are not getting london and england we are getting the actual relationship so in this way we can create profile from the users model using the relationship now let's see how to update that so we can do in the similar fashion user profile update yeah before we did create now we are doing update so what we want to update is let's say post code we want to post change the post code to one one one one here okay now if i refresh here it is giving us one because only one row is updated so it is giving us one so let's say we have a one-to-many relationship and we are updating multiple rows then it will give us the number of rows that is updated here so create return the model that that has been created and update will return the number of rows that that are affected by this query now if we go here now there is we have to we can see here now one one one if i replace now you can see here this is updated yeah and this updated add field is also changed now you can see here in every other rows they are same and here they are different now let's see if we again change it to let's say two two two two and if i refresh here now if if you closely look at this field and this field these two will be changed yeah you can see here it is changed and it is changed yeah because every time a model is updated laravel will automatically update this updated add field with the current timestamp so we have seen how to create and how to update a related model now let's see how to delete so that's also very simple we can simply call delete so this is only has one relationship so a user can have only one profile so if we perform this action user profile and delete it will delete that profile so if i run this query so it is again returning the one because only one row is affected yeah and if i go here now this should be removed here if i refresh so now you can see here that row is deleted so this is how you perform a create edit and delete using has one relationship so that's it for this video guys i hope you like this one so in our next video we'll be talking about has many relationships so one too many relationships so if you like this video then please don't forget to hit that thumbs up button and also hit subscribe button if you want to see more videos like this so thank you for watching have a great day bye
Info
Channel: Laratips
Views: 2,935
Rating: undefined out of 5
Keywords: laravel for beginner, laravel beginner tutorial, laravel tutorial for beginners, laravel 8 tutorial, laravel 8, laravel relationship, has one relation, one to one relation, laravel hasone relation, lazy loading, eager loading, n+1 issue, solve n+1 issue, laravel advanced, laravel 8 advanced, laravel advanced tutorial, laravel 8 advanced tutorial, laravel tutorial, laravel tutorial for beginners step by step, laratips
Id: NPr66D3yXog
Channel Id: undefined
Length: 41min 4sec (2464 seconds)
Published: Tue Oct 13 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.