Live-Coding: Laravel CRUD + Vue.js 3 Composition API

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello guys in this video i will be doing almost live coding of a crud with laravel api laravel 8 and vue.js an important part is vue.js 3 with a new composition api there are quite a lot of articles online about laravel and vue crud simple crud but not many of them are talking about the composition api how it works and why it is useful in practical example so i will try to do exactly that so we'll briefly run through laravel api for this for company creation so we will be building this form we can create company we can edit company get back to the dashboard edit something dot dot delete it save stuff like that so for that we'll first build the api and then the view js front the final repository for all of that will be available on github the link will be in the description below and let's begin so begin by installing a new laravel project laravel new project 4 which on my local macbook on laravel overlay will correspond to the domain project for that test then we install laravel breeze starter kit of course we do cd project 4 and then do composer require laravel breeze and then we will run php artisan breeze install breeze install also we need to migrate the database so default migration of database will be my great seed this is just my habit we don't have actually seeds here but anyway and finally we need to run npm installing npm run dev and we will have the home page with login and register capabilities okay it is successful and if i go to project4.test i can register i can use fake filler chrome extension to have a new user and we are on the dashboard so now on this dashboard we will replace this with companies form create and edit stuff now let's create the backend so model migrations and api requests so let's clear and do php artisan make model company with migration dash m the fields will be really simple so we have our company's migration file and we will have just four fields of string which is company name and then duplicate duplicate duplicate then we'll have email address and website and two of them nullable so nullable will be address and website then we need to make them all fillable in the model so we open app models company and add fillable like this so name email address and website next we create the controller so php artisan make controller api slash company controller and we will have a few flags helping us so dash dash api and dash dash resource will generate a resourceful controller but without create and edit methods because they are not needed for the api and also model company would autofill the route model binding stuff so we generate that and let's see what we have in our company controller company controller this is how it looks so index store request and then company is here so typical api controller let's bind that to the api routes api php and in here we will have route api resource of companies and company controller the api resource is different from just route resource because it doesn't cover those two methods that i've mentioned create and edit so only five methods instead of typical seven resource methods so we have api resource now if we go back to our company controller what do we need to return here for return we will create a resource file api eloquent api resource php artisan make resource company resource and it is used for the transformation for various transformation of the data in this case we will not perform any transformation so we will leave that as it is to array by default but it's just my personal habit to always use api resources and don't question that so in index we return company resource collection of company all so we get eloquent collection and parse that through the collection of company resource and we return it in the store what do we need to do first we will create a form request class for the validation so php artisan make request company request i will reuse the same form request for store and for update in this case because the validation rules will be absolutely the same so company request here and inside of company request authorize will change that to true and in the rules we'll have name equals array then duplicate duplicate duplicate again email address and website and two of them will be required so required required this one will also be email validation rule and in here we'll add rule of string for example and url url like this and then in the controller we do company equals company eloquent model create request validated validated will contain all the fields which will be described in here so if you don't describe the field in the form request it will not come in the validation and what we need to return will return new company resource with company as a parameter so it may transform the company resource file may transform single object or collection if you use the collection method next we have the show method and in here we can just copy and paste return the resource of company in the update we also should use company request here like this and we do company update with request validated and also do the same return new company request of company copy paste and in the destroy all we need to do is delete the company so company delete and what we return in terms of delete various people do it in different way i prefer to return nothing which is return response no content which will return the code of 204 so successful request but no content so we are ready with our api endpoints let's try it out let's first run migrations artisan migrate and then we have companies table so then in the database we have companies table and let's fill it in with something something it doesn't really matter we will just try it in the postman so create that updated ad and in the postman for the api client let's launch api companies we launched that and we have our data with the first record now we get to the front end part we need to install vue.js and view gs3 specifically and for that for this project we'll actually install three things vue.js view router and view loader which we'll use in laravel mix in the terminal let's clear it up and do npm install view at next because if you don't add the next it would install view too next view router app next and view loader at next we run those three and it is successful with the versions exactly what we need and in the dependencies we have all three in the package json file now we need to instruct our file called webpack.mix.js to use laravel mix and add the view here so mix js view and then post css like this so that is where we use view loader and now let's try to create our first javascript component which we will load inside of this dashboard so inside of this dashboard let's go to the actual dashboard blade and instead of you're logged in you will have router view so it will parse which route it is in the browser and load one of the vue.js components according to the route to be able to use vue.js like this at all we need to enable that in some kind of id of html tag so in our main app blade we will add id to for example this div id app and then id app will contain the vue.js inside now we go to our resources js app.js and we will enable view with the syntax of vue.js3 so according to vue.js3 we need to import create app from view and then we need to actually create that app create app what are the parameters components for now empty components will be for now empty and we create app on what tag and this is where exactly we mount to hash app so this app corresponds to app blade here now let's create our first component and the route so we go to resources.js and we create a subfolder called components then inside of that what i prefer to structure is to have another subfolder in our case it will be companies and then inside the components around that companies so we create a file companies index dot view and every vue.js component consists of two parts template and script script will fill in a bit later for now let's reach the hello world stage so hello world will be what should be on the screen and this company's index will be one of the routes so let's create the routes file now and it will be in resources.js for example let's create another subfolder routes or router and router index.js it will be not a view file it will be a js file and we will import create router create router from view router and also create web history this is a change from mode history in vue.js2 and then we will have import companies index let's call it companies index from the component which is one level above the router then we have components companies and companies index.view so we import that and then we'll have constants of routes which will be an array of routes and each route will be an object path will be dashboard in our case dashboard because it's the default by laravel brief so when someone logs in they land on the dashboard name of that route will be companies dot index and component component will be companies index the one that we used imported above and now we can export from that gs file export default create router with those routes and also options of history create web history like this so this is a change from mode history in view js2 and we export routes and finally to reach our hello world stage we need to type it all together in app.js so import router from dot router folder it will automatically catch the index.js and we need to use that so use router like this and then inside of our components we will have our component which we also need to import import companies index from components companies companies index and now we can use it inside here and let's also add dot slash here so it would be in sync now we can compile it all together and we need to run in the terminal npm run dev or we can run npm run watch and it will save and recompile on any save of our js files so i prefer to have npm run watch always in the background so whenever i save something it will automatically recompile let's see if we're successful from the first time compiled successfully great now let's try to log in so we are in our project laravel breeze we register in fact fake filler chrome extension we register and we should see hello world actually let's full refresh yep so it was cached hello world now comes not from the laravel not from the blade but from the view js now let's fill in the company's index view component with script and with the table of companies and we will do that with vue.js three composition api and before writing this article i've asked my audience on twitter and that's npm runwatch by the way so i asked do they use composition api in vue.js3 because it is possible it is still possible to create the components the old way even if you use vue.js three but more people actually do use composition api than not still quite a lot of people don't use it and still quite a lot of people are on view too which is fine but still this number is pretty strong so i would advise you would still learn the composition api because it's the way to reuse some data of your components and extract some components to avoid a huge dot view file here some of the parts will be offloaded to a thing called composable so we will create a composable which is kind of you can think about it as a service in laravel for example class that would contain all the api requests and in here in your component you would just call the features called the functions from that so composable will be a file first a folder resources.js directory composables and let's call that composable companies js so new file companies js within composables and here we'll export default what it's kind of a standard to name the composables use something so use companies in this case and it will be a function of course function and then inside will return something inside of that use companies we will define methods and properties so use companies will be a kind of a class it's not a class it's a function but it will return the object of for example companies then function of get companies for example and stuff like that so companies will be constant companies will be array but not any array to make it all reactive so to be able to access the companies in this view we will make it reactive so for that we need to add ref like this reference to use that reference we need to import it import ref from view like this if you want to read more about ref and how that works i will link that in the description below but basically you need to understand that it would be reactive variable otherwise it wouldn't change the value where we need to so companies will be filled by a function called function get companies inside of that we will make axios request axios get slash api slash companies and for that we need to import axios actually import axios like this then axios get should be await because it's async function and that's why the whole function becomes async so let's change the syntax to no parameters and async function like this so this get companies is an async asynchronous function without any parameters and now nothing is underlined and we assign that to a response so we will get a response from the server and then the ref part comes in where we can assign companies value equals response we have response data and inside of that data laravel comes with data as well according to eloquent api resources remember in the postman this data so response data is generally anything that comes from the server and then inside there's another data so it's confusing but it's actually two different things and we export that get companies here in the return so now we have a composable file which we can use inside of our company's index here and we actually imported import use companies from composable companies great now in the view 3 syntax we need to export default and define the setup method here and inside of the setup we will return companies to be used in the template so we will have a table of companies i will build that in a minute so we return that and we will fill that in by returning that from the composable so constant companies companies and get companies is the thing that we need from used companies i know it sounds confusing just it will get it all together in a minute so we have used companies we used from the composable it's kind of like include the service include the file and from that we need not everything later we'll have more methods in that composable but for this component we import only companies and get companies method and we need get companies method to be called automatically for that again view three syntax we import on mounted from view and then it's kind of like mounted method what it was in view two so unmounted we called get companies and that's it so what happens here we load the use companies on mounted we automatically call the get companies from the composable inside of that composable companies receives the value and since it's a reference it will be available here in the companies and now in the table we can build our table with actually listing the companies so instead of that hello world i will actually paste the table to save you some time because it's not about html this lesson is not about html so it's a typical table with tailwind classes with four columns of headers like address website name and email and then we have view syntax for v4 item in companies so this is where we actually use those companies and each item will have a key item id which we will use later in the edit and in the delete and this is a typical vue.js for each statement with v4 and we show name email address and website nothing really too fancy now we save it should be built built successfully because i'm running npm run watch and we refresh the page and instead of hello world we refresh and we have our table with companies exactly from the database so we have the table and the next step in the crotch should be create and edit forms right but i want to make a different path take a different path and take care of the delete now because delete is relatively easy function but it will show it will be showcase of how composables work for reusable data so in the composable we need to define another method of destroy company by id so we copy and paste and let's call destroy company then the parameter will be id and then we need axios delete with the parameter of slash dollar id here and we don't need any response and we don't need to change company's value i will show you why in a minute so we delete that part we delete this line so the only thing in destroy company will be just calling the delete api and we need to make that method also returned in the export now we can use that destroy company in our component here first we catch that here destroy company and then we define a local delete company or destroy company it should be a different name so constant delete company will be async function with a parameter of id and inside of that body we will call await for destroy company with the id so see what is happening inside of that template we will have a button i will show you that in a minute which we'll call delete company which in itself will call the destroy company and refresh of the company's table will happen with await get companies so see how composables work there is nothing about the company's variable here companies are taken care of by the composable so we just call the method of destroy and get the companies and we need to call that destroy by a button for example let's build another th without any stuff inside so there's no spam just empty header and in here we will have let's copy and paste and instead of item website we'll have a button button delete and inside we'll have at click will be delete company company by item id and one thing i forgot to do why autocomplete didn't work it's not in here delete company and let's add some classes to the delete button i will paste it from my notes or tailwind classes and let's see how it looks now we save the build should be successful we refresh the page and we have a delete button what it does it should delete the data but first we need to ask for confirmation right so inside of our delete company and that's the whole point of delete company works with the current component with the current form but destroy company is actually working with the api so it's kind of a different separation of concerns which is a general good practice in any programming language or any programming framework and the composition api kind of takes care of that separation so our main view component is not that long but inside of that main view component we need to take care of the confirmation so if not window confirm are you sure then we return like this and also another thing i've noticed in the company's js in the composable we should use a more simple syntax like id because this was kind of undefined or unused so now it should work build successful we refresh the page we have delete if we click are you sure cancel nothing happens but if we click ok the company is deleted from the database and visually so again see how composition api works with the composables so composable is kind of like a service that takes care of all the api requests and in here it makes our main component a bit smaller now let's take care of the create and edit forms so first we create the component of course companies edit so we just do file save as companies create.view first so we will do companies create and for now also let's reach the hello world stage so create form coming soon for example with no scripts for now and let's make the route for it in the routes index we will import that companies create from companies create here then we need to copy and paste here with a comma so the path will be companies create and the name will be companies create and the component will be companies create next in the company's index on top of the table let's add a button or a link and we will use router link and i will just paste it from my notes again because it's html so it still went a lot of classes on top of html and this is what we care about so router link to the company's create name we use the name the same as this one and then we should be able to create the company let's build it again successful and let's refresh the page now in our table we should have a button which should lead to create form coming soon exactly what we expected now let's build that form so again to save your time i will paste the form for html and we'll explain it to you so it's a typical html form with a few things on submit it will call a vue.js function called save company which we'll define in a minute in the scripts then we'll have errors if there is a validation error so this will appear errors will be a string and also we will have a form object which will be a v model for form name for email form address and form website so this will be all defined in the script below and we do export default and then again view three syntax setup what do we return return something what do we need public in the template we need form we need errors and we need save company method now let's define them inside here form will be a thing called reactive and reactive is another thing similar to reference to ref but for more complex objects so in here we'll have a more complex object of name will be empty and then duplicate duplicate duplicate email address and website address and website to use that reactive we need to import it so import reactive from view like this so we define the form again so it would be refreshed wherever we need it we need to use reactive and it will be a const then we need to create the store company's method in our composable so in companies.js let's do copy and paste and then store company async without parameters we don't need any parameters axios post to companies with actually we do need the parameter of data and we will pass it here so data and then we don't need any result like in this case we will just redirect to another route so after store company successful we will do router push to route name of companies index to use that router inside of composable we of course need to import that import use router from view router here and inside we define const router equals use router like this semicolon here now it should be working so router push oh and i forgot a weight here await router push for now we don't care about the validation we will tackle that in a minute for now let's make store company higher than destroy company because it's more common and let's make it returnable so store company here as well now i can use that store company in companies create here so save company will be another const save company will be async method which will await for store company and that star company of course comes from the composable so we do import use companies from composable companies and then in here in the setup we need store company comes from use companies here and of course it should be const here and i've made another some syntax error here or of course like this so we will call save company and it's exported here and on top it is safe company which will in turn call the composable api with store company and we will have a parameter of form in a way of this javascript syntax form and also we need to import errors from that composable for now it will be empty so we have errors in the companies js here const errors will be empty errors actually ref of empty and then we need to make them come here errors great so now nothing is underlined and let's try it out now if we refresh our page we will get laravel 404 not found and there's one more thing we need to take care of from the laravel to be able to use view router properly so in the routes web php on the very bottom we need to add route view any so on any other routes than the ones mentioned above so any like this we need to return the dashboard so the same dashboard which will trigger the vue.js component of ujs application where any equals anything and that anything is expressed like this and also let's add a middleware but to be honest it's a mismatch in my application and i noticed it only now that the dashboard is actually under auth but the apis are public but for the consistency of the web let's add middleware auth here so the vue.js application would be accessible only by logged in users so now if we refresh our page we have slash company slash create and we got 404 but now we don't get 404 anymore because it's loading the view router and the view router then matches that url to the company's create component let's use fake filler chrome extension to fill it in and let's click create and as you can see we have a new record in our table it was redirected to the route of companies index but that redirect happened not by refreshing the full browser the full page it was just this part the application of vue.js was refreshed finally validation and validation if you noticed on top it's v if errors and by default the errors are empty and as you can see we don't do anything with errors here in our component and that's another thing where composables are handy because they will take care of everything so errors come from composables and in here we should set if store company has some validation errors we will fill in the errors here so try and then catch catch exception or error if error responds status equals 4 to 2 with three equals then we will have errors value equals something and for now for the very beginning of that store company we will pass that we will assign that to empty errors value and in here i will paste it from my notes to avoid typing for quite a long time is just a javascript thing off for each of response data errors because it's quite a complicated structure of json it's errors then fields and then each field may have more than one error so we're just parsing that maybe there is a shorter way to do that if you know that just shoot in the comments but basically we're constructing it error plus space and that's it let's try it out build successful we refresh the form create company we don't fill anything we create and we have these four errors so email is required of course it may be more pretty but i'm not a designer and this is outside of the video the video is about functionality but basically you see the validation error and final thing was left in this lesson is companies edit which will be pretty similar to companies create so i will just file save as companies edit and we will repeat the same steps so routes index again duplicate here companies edit from companies edit dot view and in here we will also copy and paste here with a few changes so the path will be companies edit but with id like this the name will be companies edit and the component will be companies edit and another new parameter will be props true which means that we have a parameter for this case and probably this one should be upper case okay now in our companies edit let's again let's reach hello world stage so template edit form coming soon script is empty or in fact let's delete it so companies edit and in our company's index in the template let's add another button or link for example router link to name of the route will be companies edit and also there will be a parameter so params equals id wait id item id so the same item id which is in the for each here but just we will call a different route and we will close router link and we'll add the same class the same long tailwind class to the router link here the build is successful we go to the page we have the table let's refresh it and we have oh i forgot to edit the actual text of router link so it should be added here and also let's add a class margin right to the build should be successful again and if we refresh okay we have edit and if we click that is not correct i've messed something up of course a typical scenario of one symbol messing things up so router link two should be here and then see even the colors change so now again build successful we go to the dashboard again and we'll click edit again now edit form coming soon great now let's build that form and in the company's edit view again to save you some time i will just paste the html and will explain it to you so almost the same as companies create with a few changes so errors will be identical then save company will be a method and in here instead of just form we will have company the full object so let's define that here and we will get it from composable so first we do import use companies from composable companies then we have export default like this return what we need to return the company and the method of save company and inside of here what we need from the composable constant company get company equals use companies like this and of course i forgot that i need to have a setup method it's all in the setup method here so it's not return of export default class it's return of setup method then get company let's define that in the companies composable so get companies will be almost the same as get company by id and axios get should be api companies plus id and we have company's value but also we will define a company also ref with empty array so company and company value will be the response of this get company and let's make it exportable here and also company should be here so we have company and get company and we'll use that get company in the unmounted so unmounted we will have get company by props id props id we need to pass the props here in the setup method that's why we defined in the router here props true and this is the id and we need to define that id actually what will be our prop so props will be id and it should be required true and type string like this and then on mounted we need to import unmounted import unmounted from view and again wrong way how to define the props it should be outside of the setup here like this so we define the props and then we define the setup method comma here cool so on mounted we will get the company the get company will assign that company and in the form company website and company everything will be filled for now let's comment out save company and i will show you how it actually works build successful and if we refresh that we have a form with fill in the data by company id 2. now let's submit the form so save company will be const save company will be async method which we'll call save company from the composables oh wait but we don't have that method yet let's call it update company update company by props id will pass only the id and update company should come from the composable we haven't created it yet update company and now let's create that let's uncomment save company here an update company will be pretty similar to store company so copy that paste and update company the parameter will be id and axios port to companies plus id with the data from where we have the company so this is another thing what composable does we don't need to pass the company here because it's already inside of the composable and in case of success we do again router push to the index otherwise we parse the error and final thing here is we need to have update company here so again in the company's edit what do we do we save the company that's on form submit then it calls the update company from the composable and the composable redirects to the index or shows the error let's try it out our form we refresh and if we do dot dot here we save and nothing happened and i've traced it down behind the scenes to four to two in the network so name is invalid which means that i didn't pass anything through and the error was that i need to pass company dot value not the object and now if we have build successful let's refresh the form close the sidebar dot dot here save and now it is successful and if we have any validation error for example we delete that we save and nothing happens again let's go to companies edit errors are underlined why oh of course i didn't make it public to the template so errors company and save company and we need to get those errors from where from here from the composable so now build successful refresh the form refresh the form delete the field save and we have our validation error so that's it we've built our crud with composition api with vue.js and laravel of course it's a really simple example but still in this quite long video i want to give you the core thing how the composition api works in vue.js three with laravel api and from here you can experiment with more complex forms with different field types like drop downs and stuff like that if there's anything that was wrong in this video i was kind of live coding so maybe i missed something then shoot in the comments below and if you want to thank me somehow for doing this long tutorial you can check out one of the three products that you can see on the screen below which is my courses quick admin panel generator of admin panels which actually includes view version or set of my live wire kit components and see you guys in other videos
Info
Channel: Laravel Daily
Views: 2,264
Rating: 4.9823008 out of 5
Keywords:
Id: KfaZRBdN2as
Channel Id: undefined
Length: 41min 3sec (2463 seconds)
Published: Wed Oct 06 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.