[01/10] Laravel Travel API: DB Schema - Models and Migrations

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello guys so yesterday we started larval mentorship course on creating travel API and today you will see a video about lesson 2 about creating the database models and migrations with some fields on Top This is the screen how you would see that if you are reliable daily premium number with text based version and with access to GitHub and additional links but on YouTube I published just the video version and I changed my mind on something I thought to edit down the kind of summary version so from 21 minutes lower it down to some 5 or 10 minutes but in the end I thought it would be unfair because it would be missing quite a lot of details and also it's an extra work for me to kind of lower the quality doesn't make much sense so on YouTube I will still publish full versions of video course as it is on laravel daily premium so premium members would get extra access to GitHub access to Discord full text based version where you can copy help you the Snippets still quite a lot of benefits to be a premium member anyway I hope you will continue creating that course with me I hope some of you try to create a database structure already from yesterday's video and now you will see my version of it tomorrow the next lesson the task for you before tomorrow is to create the first public endpoint of listing the travels with pagination and with filtering only public travels the full description of the job description is in Google Docs and I will link that in the description below and tomorrow we will talk about the end point but for now creating the database so we start creating our database and client described it with Fields so we need to just implement it but there will be a few caveats along the way so we'll start with creating laravel project laravel new travel Dash API that's how we will call that then we CD into that folder and we will generate row stable travel stable and tours table with the model as well in users we don't need to change anything we will just need to add relationship to rows many to many as it says so CD travel API clear and then do PHP artisan make model roll with migration that's the first database table for us then I opened my phpstorm I added a string field name in the migration and in the role model syllable name this is needed so we would be able to do something like role create with Fields here with array of fields if you don't do fillable then this would throw an error the alternative approach to fillable is guarded so instead of doing fillable and then listing all the fields you could do guarded and then provide for example empty array so these are the fields that are not fillable which means every field is fillable I personally prefer to provide syllables instead of guarded because for future developers then it's perfectly clear which fields are actually fillable in the database without looking at that database or migrations next according to the client specification we need to create this rows many-to-many relationship from users and to do that in phpstorm I open the terminal and we need to create a pivot table and the name of that pivot table is important so create raw user table it needs to be exactly that not roll users and not users roles the rule is that those two tables should be an alphabetical order lowercase in singular form if you specify the table name in that order then you don't need to specify that name separately when creating the relationships so if we open that role user table for now we just fill in for an ID to roll ID constrained and for an ID to user ID constrained and by the way I do remember that the client asked for uuids to be used in the specification but I want to discuss those uuids separately so for now we'll create all the database with regular IDs and primary keys on auto increment and then we'll transform that to the euads at the end of this lesson so we have the pivot table and this constraint by the way thing for those of you who don't know is just a shortcut for you can do it manually references column ID on table on rows so constraint is just a shorter way to write the same thing and also in constraint you can provide parameters which we will do later in this lesson so you can provide table name so that may be useful if your table name is not standard okay we have a pivot table and then to make that pivot table work in the user model we will add a relationship I have a feeling that we will query the rows for the user so we'll check the permissions but we don't need the relationship the other way around that's my personal preference for example One belongs to many many to many you can create both but I'm a bigger fan of creating relationships when we actually need them so for now I will create just rows return belongs to many role class and a thing that I started practicing more and more lately is to provide return types so in this case we have belongs to many which was automatically by phpstorm added here on top that return type is optional so you don't have to do that but that provides extra Clarity for other developers in the future and that's kind of a good habit to adopt especially since lateral 10 skeleton also contains return types everywhere now if you go back to the specification of the client the next model is travels and here we'll have a few interesting things like Slug and virtual column number of nights but for now let's just generate that model PHP artisan make model travel with minus some migration you can actually create more than just migration so there are more Flags like generate factories Cedars and others but again I'm a fan of creating things only when you actually need it so I will create factories and Cedars one-way ride automated tests later in this course for now model and migration and here not sure if you've noticed already an interesting thing create travel table generally laravel pluralizes all the forms so if we provide travel it should generate travels table right but in this case travel is irregular noun irregular word which doesn't have plural of travels although the client specified it as travels here in plural form and you can quickly debug the plural forms of things so you can do PHP Artisan Tinker for example and then inside of Tinker you can do Str any word and then do plural string function of laravel and it will return you travel for example if you provide I don't know toy for example the plural is toys so this is a proof to you that travel is a regular word now what do we do with that we have a few options first leave it as it is but then we don't implement the specification exactly as it is and also for international audience of Developers for example if the project is then supported by international team non-english speakers wouldn't know that travel is a regular word I have a feeling that it's better to move away from correct grammar in favor of clarity in the code so what I would do let's close the terminal I would rename travos here and also rename the file itself refactor renaming phpstorm travels table but that is not enough we can create the fields but then we need to specify that if our model works with table name that is different from default pluralization we need to open travel model and specify fi table equals not travel but travels like this interesting case for quite a long time I haven't encountered irregular nouns in larval so it's great that it's appearing in the scores kind of by the way and then we fill in The Columns of migrations and fillables I've done it from my notes pasted it here to save you some time for me just typing what I can comment here default of Boolean could be true or false string slugs should be unique and we will get to that a bit later in the lesson and slug will be automatically generated and also number of days will be a real field in the database and number of nights according to the original specification will be a virtual column an accessor in the model speaking of the model we add the same things as fillable in the model okay so we're good with Fields now let's get to those extra Behavior Force log and number of nights so slug for travels I've opened the console here terminal on the left hand side head so you would see it better and what is Slug if we open PHP Artisan Tinker we can do Str for example my travel will be the name of travel and then slug that it will be SEO friendly name so lowercase without spaces with dashes and we can generate that easily as you can see with laravel and if we don't need it to be unique then that's all we need to do so I will show you this way if you don't need that uniqueness and then I will show you perhaps more flexible way but with external package so let's close the tinker and let's generate Observer Observer class PHP I just make Observer for the model of travel so travel Observer and then we specify model of travel like this let's close the terminal for now and in travel Observer interesting thing that by default Observer generates some methods like created updated deleted which which means what would happen after the record is created updated deleted but in our case we need to modify the record before it is saved in the database not after so we need a method called creating not create Ted it is not generated by default but we need to create that manually and we delete all the other methods because we don't actually need them so when creating we will modify the travel record like this so travel slog would be Str travel name to slug like this so this will be our Observer method and we need to register that observer in event service provider there are two ways to register that in event service provider for example in boot method we can specify travel model observe and then provide travel Observer class and both of them are generated with my phpstorm here added on top or if you don't want to pollute boot method it and if you are a fan of configuration you can provide that as array observers protected observers equals array and then model and array of Observer files so travel model class and it will be array which observers are here so travel Observer class like this so two syntax ways and now if we try to migrate the database so far and create that record PHP Artisan migrate so if we migrate we have those tables and if we Now launch PHP Artisan tinker and try to create travel create with field of name for example some thing and also add a few other fields like description and number of days class travel not found of course it should be with all the model name space in this case and as you can see slug is something automatically generated which means it works with Observer but it's not unique so if we try to create another travel with the same name we would have error from the database because in migrations we specified that this should be unique but on eloquent level we have an error now so instead of doing that with Observer we could of course add that logic into the Observer and check for the database but there are a few laravel packages that would do it easier so let's just undo everything in event service provider and let's remove that travel Observer as well just delete the Observer folder and instead let's use this package eloquence loggable by Colin vbrock very old but very good package alternative if you want Alternatives it's spicy package laravel sluggable they work in a similar fashion but this is older one and my personal preference because I just am used to it so to install that it's very easy actually installation is just composer require so in terminal we do compose or require and then in the model of travel we need to specify two things we need to add sluggable here and then also sluggable method where to take the source of that slug what to generate it from from The Source in our case Source will be the name so we just copy and paste the method of sluggable and change that to name and now if we repeat the same thing in Tinker let's clear it up and launch Tinker again and repeat create see the result it will automatically make a different slug if the name is unique so there will be something too another one will be something three and so on so if you need the unique behavior for your slug I do recommend this package next we have this number of nights virtual column I would kind of interpret that as not a real column in the database but calculated computed column which in eloquent terms is accessor so we can just create accessor of number of days in the travel model here and I will use laravel 9 newer syntax 4 accessors public function number of knights which returns attribute and attribute comes from eloquent casts will return attribute make and attribute make has get and set both or either of those functions so we generate only get in this case and we need to have function from value of number of knights but in this case the attribute is calculated from another value in the database another column of the same table which is number of days so we need to pass attributes by default and then we return attributes number of days minus one like this so this is the syntax so now if we generate a new travel record again let's open Tinker let's do travel create and then do travel for example travel latest first and then Echo travel number of knights the result will be four you can also use alternative syntax older syntax of laravel accessors and mutators which is get something attribute and set something attribute that syntax will still work in laravel 10 and Beyond from what I know it isn't planned to be deprecated or removed so if you prefer you can do public function get number of nights attribute like this and return this number of days minus one like this it is shorter but it use string magic of function name so not Everyone likes that but basically use whatever you prefer I will stick to the newer syntax of laravel 10. the final model and the final database table is tours and here we will encounter two things that we need to take care of separately travel ID will be again irregular noun and then price should be calculated with accessor annutator and I will show you that in a minute for now just artisan make model tour with migration nothing really fancy and again to save you some time from me typing I filled in from my notes so these are the fillable fields for tour including travel ID as relationship and in the tour migration this is what I meant by irregular noun if we leave it like this then the migration would not work let me prove it to you by actually running the migration pH partisan migrate the error will be that it tries to search for the table of travel which doesn't exist so we can fix that by specifying which table to look for and also let's fill in the relationship in travel let's create hands menu for the tours and actually I'm a bigger fan of creating the relationships first before attributes because relationships are probably the most important things in the models the most widely searched for so I created a bit higher so tours again has many returned and return tour class again I think I have a feeling that we will query the tours by certain travel but we will not at least for now need the other way around relationship so I just create as many and I don't create belongs to yet and with this model as I mentioned we have price as a separate logic so the client says this prices are integer multiplied by 100. it's kind of a well-known rule in the database space that you should not store money related fields as floats as decimals you should store them in sense in integer and then transform it back and forth when saving or getting the data so this is exactly what we need to do here so in the tour model we will create again attribute public function price attribute I will again use a newer syntax of laravel 9 return attribute make and in this case we will have both get and set get function value will be when getting we need to divide by 10 by 100 sorry value 100 and when setting the data function from value would be multiplied by 100 which means that in the database we'll have integers all the time but when showing to the client on the front end it will return with sense and final thing that we need to do in this lesson is to take care of uuid as primary keys I deliberately left that as the last part of this lesson because maybe not every one of you would need those and maybe you would be okay with database structure like this as we currently have but if we do need uuid these are the changes that we need to make first in all the migrations so create users and others we need to change table ID to table uuid but not just your uid we need to specify that the field name should stay the same ID because otherwise by default it is uuid and also we need to specify that it is a primary key like this so we need to change that line in all the tables that have Auto increments so in our case it's users then rows then travels and tours in four tables then since we have primary keys with uuids we need to change foreign keys to the uuids so everywhere we have foreign ID we need to change that to foreign uuid laravel has that in migrations so we just change those two letters basically for new uid from tours to travels enroll user same thing so foreign uuid and for new uid here so that's it and then the final change in migration is related to personal access tokens instead of morphs to tokenable which is actually a user ID we need to have uuid morphs like this for polymorphic relationships like this so these are the changes in migrations and then so it would generate the uuids we need to specify in all the models of eloquent a trade has uuid so in the user model this function is relatively new in laravel since 9.30 you just specify has your uids and then laravel takes care of everything how those uuids are automatically generated and of course that has uids should be in the use section so we do that in the user model in the role model has uuids like this and tour model on top of has Factory we have has euids and also travel model has uuids now let's re-migrate the whole database fresh it is successful and let's try to create that travel record and let's see if your uid is successful so autism Tinker again and travel create and we have ID as this thing not Auto incremented number but uuid value so we finished created our database schema which is kind of the most important part in the project beginning as I would say and let's create the visual schema out of that you can use any tool you want my favorite is D Beaver which generates the visual schema by just double clicking the database so you see this and you can see that our database is actually divided into three sections so you could say laravel system tables these four ones then tours and travels and then rows and users so that's it for this lesson I know a lot of content in one lesson if you have any questions let's discuss in the comments or on the Discord
Info
Channel: Laravel Daily
Views: 9,394
Rating: undefined out of 5
Keywords:
Id: 9aIVmiL3Xks
Channel Id: undefined
Length: 22min 42sec (1362 seconds)
Published: Wed Jun 07 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.