Laravel 6 Beginner - e8 - Form Validation

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] now that we have a way of displaying our services and grabbing them from the database I want to take care of adding services dynamically in the previous episode we were adding the manually through sequel pro or even through tinker but I really want to be able to do this through a form and in doing so I want us to talk about levels validation system which is very robust and you're gonna use it all the time now the first part of this episode is kind of a review and then after that we'll go ahead and tackle that form in order for us to take care of this let's create a dedicated controller for our services it is something we don't have right now if we visit the code right now and we go to our routes file the web dot PHP you notice that we have this hello controller and it's going at services so not exactly a dedicated controller let's do that right now back in my terminal I will actually bump over to a new terminal in the exact same directory that way my PHP artisan Cerf is already running in the background now let's go ahead and create a new controller PHP artisan make controller and let's call it service controller this will generate a controller for us and automatically namespace it and everything else so now inside app HTTP controllers we have this new service controller as a first refactor let's bring in whatever code is inside the services hello controller and bring it into this new dedicated service controller so in my hello controller I will actually cut out that entire services method that we had before and let's go ahead and paste it in at this point this services name for this method is very redundant because we are inside a service controller and now we have this services method really doesn't make any sense but in fact this would be considered an index method in a restful controller we'll dedicate an entire lesson to restful controllers but for now index is one of those verbs that we're going to start talking about more and more as we get into developing in al-arab away using restful controllers now that we've brought this method into the service controller the next step is to change our route file we are no longer hitting a hello controller we are hitting the service controller and we're no longer in the services method but we are in the index method I'll hit safe I'll head back to Chrome and if I hit refresh and you did everything correctly nothing should change this refactor was purely just to set us up into something better okay back into my service controller remember we are loading this services view but it really again doesn't make a lot of sense for us to have a service controller with a view of services because if we had another method in here what would we call this would it be services to and then services three it's not great let's come up and establish a nice naming convention for our views the way that I do it is I grab this right here so service without the controller part and I create a directory every view that this controller is going to use is gonna sit inside that directory and then I grab the method name in this particular case it is index and I save that inside the service directory it's a lot easier to see than it is to explain so let's just drop right in and do that refactor inside my resources views I'm going to create a new directory for service again service is coming from the fact that this is the service controller so if my controller was called customer controller then the directory name would be customer if the controller was called post controller then it would be called post all right so we have this service and now this services I'm going to drag it into services I'll move it and then let's rename it it will rename that to index that blade that PHP again index is not like your typical index dot PHP file has nothing to do with that it has to do with the fact that this method is index picture this if I am looking for the particular view being loaded inside the service controller index method then all I need to do is go to my services directory and find an index dot blade if I had another method here called creates then I will go to my services directory and then to create that blade that PHP that's the way this naming convention will work this is not letter L specific this is something that I do that I find to be very easy and flowing so instead of services we're now going to load service dot index and again if I hit refresh we did everything correctly nothing changes again we're just refactoring into better more maintainable code nothing to do with actually implementing anything new we're just trying to establish some grounds on how applications should really be built in the real world it would serve you no good for me to show you all this things for beginners and not show you a real workflow of how an application is actually built because when you go out to build your own applications you don't know how to start so this is very important naming conventions are important in laravel it's something we've already touched upon and on top of that keeping your application organized is extremely important as it grows and grows and grows if you don't have a concise very meticulous method of organizing it it's going to get out of hand and it's gonna be difficult to maintain that's what it's considered an unmaintainable codebase it's one of those that does not follow any particular rules and how they name things and how they store files it's very important for you to have very organized applications ok let's move on to the next step again I want to have a form and I want to actually add now I could go ahead and add its own method but why don't we just add it to this new index blade we're gonna have some services but right before this let's create a form for now the action will leave blank and I'll have an input field here of type text and let's give it a name of name because this is going to be the name of my service and then let's go ahead and have a for add service it's not gonna look very pretty but it'll get the job done again I want to be able to fill this out and then add service now if you notice here when I click on this it kind of gives me some suggestions now typically on something like this these are not repeatable fields if you want to turn that off you could say autocomplete equals off and now it will not give you any more suggestions just one of those small tips that will make your application a little bit better so again I will want to type in here and then click add services hit something and of course I want that service to be reflected in my new list okay now this form it's going to be method of post and then on top of that what is the action going to be well our action is a route a URL right we need to hit a particular route so what if we hit slash service right now we're using this services as plural but I do want to start using service instead of services so our route will be slash service so let's go ahead and create that and I do need to create a little bit more space here and let's create a new post route it's going to be a post route again because my method is post so it's not a get route it's a post route to create a post route all I need to do is change this from get to post and like I said I want to switch from using services to using service singular so I'll go ahead and make that change as well and then I will still hit my service controller but this time let's use the store method as the name would suggest the store method stores a new record now one thing with this change is now I need to actually generate my new links because if you remember in nav that blade I'm still going to slash services let me go ahead and go to single service and let's go ahead and visit the right page here and there we go no big changes there I can still type in here hit add service this time I get an error but we will start to work through those ok great so what do we need to tackle next so we have this form and it's supposed to be hitting slash services with post but right now we know in my route I am calling this store method but the store method actually doesn't exist in my service controller let's go ahead and add it in and then just to show you that it's quite not working just yet I will actually just died and dumped inside just a quick string here if we are in fact hitting that store method then we should see the text inside okay let's give it a go and let's see what happens I will type something in hit add service and we get this for 19 kg expired okay this may be a little confusing at first however laravel is helping us stay protected this page expired is what's called CSRF protection and what it does is it stops anyone from submitting to our form that isn't from our actual application it would basically be as if somebody made their own form but was redirecting the results of that form into our server most of the time you don't want that to happen sometimes you do but most of the time you don't the way that letter will checks if this form is coming from your server or somebody else's server is using a CSRF token letter well makes this very simple the only thing you need to remember in order to make this work is that inside every single form you need to add this particular blade shortcut and it is at CSRF and i will actually just show you what that actually does so what it does is it as a hidden field in our form and it is right here with a token so this token is generated on your server whenever you refresh the page then level is able to match up that token to your server token and if everything is good to go then of course this form is coming from us somebody who is actually creating this form outside of our application would not have access to this token generation process and thus it would fail so that's the way that that works now if I hit add service this time it does work so as a quick recap on that again CSRF is a protection for cross server meaning that somebody in a different server can't submit to your application now there are several reasons a little bit outside of the scope of this particular lesson on why you would want some protection against that but again trust level in its opinions levels very opinionated but it does it for a reason you can always step out of the box once you are ready but for now let's stay in the box and I promise you it will all make sense okay so let's keep going to the next step now we are in fact actually getting into the store method and we know that because we saw the text of insight and here it is great so how do we grab this name remember we are passing in a form that has an input with the name of name okay so there is a helper function in level which is adequately called request and to request you can simply pass in a string with the request value that you are looking for so I am looking for name alright let's go ahead and hit refresh we'll say yes go ahead and resubmit the form and if you remember DFG is actually what I typed inside this form let's create a new service here maybe very cool service and now when I hit add service there we go so we do have very cool service so armed with this information we are ready to make the very first implementation of this creation and we can do it in the following manner so we can say ok my service and let's go ahead and new up a new app service model I want to set the service name equal to request name remember again name is just the input and then let's go ahead and save that to the database but then after I'm done with this process I need to actually redirect back to the same page so I can simply return a redirect back and there we go so we're simply going to redirect back let's give this another go I'll hit continue and there we go so we have very cool service I'll type in some gibberish add service and there we go when we type into this form we know that it hits this service route as a post request notice that this and this are exactly the same and that's nice because we can reuse names we don't have to come up with these creative names this is restful controllers we'll keep talking more and more about this but when it's a get request it will respond with the index method and when it's a post request it's going to respond with the store method ok then we hit this store method inside the service controller where we actually grab a brand new service model we assign the name using the request name and then we save it and then we redirect back meaning we're back into my index because that's what we came from so that's working we saw it working however something can happen what if the user leaves it blank and hits add service whoops we get this big error that's because right now we are not validating this form at all we are blindly creating and inserting into our database without any error checking you should never ever ever trust your users whenever it comes to submitting forms you need to be extremely diligent about what they send you and you need to make sure you sanitize and validate every single piece of data every single time I can't stress that enough Lenovo makes it extremely easy to actually validate some data and it uses that same request helper function that we already use let's create a new variable we'll call it data and then we'll say request this time we'll leave it empty but then we'll say validate and that is the keyword right here we're going to validate our request inside of this validate you need to pass in an array this array will contain a line for every single input field that you have whether their input fields or text areas whatever you have in your form in our case we just have one for name and then you're going to match that up to some rules now there are hundreds of rules that you can use but in reality you'll use the same four to five different rules the most important one to know is required required we'll make sure that that input is not blank that's exactly what we're looking for right now so let's give that a go I'll hit back I'll go ahead and refresh the page actually we don't even need this and that should still work and now I'll leave it blank and hit add service and notice that this time nothing happens but also notice that we are not giving the user any feedback at all as a matter of fact we don't know what happened we don't know why it didn't work luckily for us there's another blade syntax that will help us with that and it is at error so we can use it like so we can say at error and we can say okay if you have an error for name then I want you to display the name now the name will come in as a variable of message so let's just go ahead and type in message and then let's end error okay this might look like a little bit of weird syntax but check this out now when I hit request the name field is required we're actually giving our user some feedback how cool is that level is actually smart enough to even generate a very nice sentence for us telling us exactly what the requirement was that we did not meet how awesome is that it will really save you some time during development so that's it just like that we are doing validation and on top of that we are actually outputting out some errors you can style these errors in any way shape or form that you would like we can wrap this in a div tag and just for now let's go ahead and give this maybe a color of red typical or something like that and sure enough there we go we have nice red validation error awesome what if I had a new rule where a service needs to be at least five characters so if I type one two and hit add service it does add it but I want to create a minimum with of five characters the nice thing with validation is that we can tag on as many validation rules as we want it basically just creates a stack for us to divide them you're going to put a pipe that's the big vertical character that is on top of your return key and then we can add another rule so we'll say okay minimum needs to be five let's try that again so now I'm going to type just a Q hit add service and there says well the name must be at least five characters how awesome is that okay what if I had another rule that maybe a service needs to have a maximum of ten characters I know it's kind of a crazy rule but let's add another pipe and let's say max is going to be ten okay so now let's go ahead and type a lot of characters hit add service and it says up the name may not be greater than 10 characters how amazing is this validation so just like that very simple you can stack on as many of these rules as you would like I'll go ahead and delete the max rule because that one doesn't really apply so how do we find all these validation rules well in the documentation of course let me show you if we go to layer Volcom we go to the documentation let's go into the basics and then go to validation validation is going to have available rules it is right here available validation rules and these are all of the validation rules that we can use for example another common one you're going to use is email you're going to validate that email addresses are in fact emails and not something else let's check out some of the other rules that we used we use the required rule and that one is right here and it simply says the value cannot be no the value is an empty string or it's an empty array or it's an uploaded file with no path very cool so check out all of these rules here that you can use there is a way of even generating your own custom rules but that's more of an advanced topic but with the rules available right out of the box you should be able to validate 99% of all of your forms again another great tool because it saves you time during development there's even rules about dates there's rules about JSON and size and same that way you can make sure that two fields are the same as each other there is literally tons and tons of rules so definitely some homework is to explore some of these rules okay so with that we're adding services we're actually generating so if you stick with me just a couple of more minutes let's clean up this controller just a little bit this store method it's quite heavy right now so let's refactor into a little bit more manageable of a controller notice that I saved this to a data variable and you may be wondering why would you do that if you didn't actually use it let's do something let me die and dump that data I want to show you what it actually gives us I'll go ahead and enter some gibberish add this service and notice we get an array with name and then we get that all together well this is good we can use that data but it may not be very clear at first because of the way that we're actually creating this record so let me show you a different way that you can create a brand new record in your database you could do it using a static method call so it would look something like this will say app service : : creates and to create we can simply pass in data level smart enough to map name as in the column name in our database to that so as long as you've named your fields exactly the same way as your database let's go back to the create services table remember that this is called name if this was called maybe service title in that case my form field should also be called service title again naming convention very important in level now with this this is going to give us an error because level actually has something called mass assignment protection it is a little bit complicated in terms of what it does but the effects are very easy to understand he will not allow you to do something like this out of the box because you need to be explicit about which fields are actually mass assignable and level considers mass assigning a field if you are passing in on an array of data with a bunch Fields inside of it so let's go ahead and see that error and then I'll show you how to fix it I'll actually show you two ways how to fix it I'll go ahead and hit refresh which will just resubmit my form and when I do I see this new masse assignment error again I want to show you the errors so that when you run into these problems you know how to fix them so it's actually telling us what to do it says you need to add name to the fillable property and this doesn't make any sense at all but the one clue that we have here is that it is inside app service if you recall that is our model let's visit the model the model is sitting right here right on the app directory and it's called service dot PHP we talked a little bit about the smaller but we actually did not do anything with this fight so there is this fillable property that you can add to your service model so we could say protected fillable and fillable will equal an array now inside of this array you're going to name each particular column that you want to be fillable the one that we are interested in right now is the name so let me go ahead hit safe and hit refresh again there it is and now it works so again if you have some forms you need to be explicit about what is fillable so what we've done in the process is actually clean up our controller notice our controller how much cleaner it looks let me undo a couple of clicks here and let me show you the previous implementation and here it is so this is what we had before but with this small change we are now here so a little bit cleaner we can even inline this if you wanted to this is an optional step you don't have to take this but you can actually inline this right here and now we end up with this again it's up to you which one you would rather take I'll leave this one like so but you can always inline straight into your create method very useful and very nice and easy to do okay I told you I was going to show you a second way if you don't want to have to put in every single field in here instead you can turn mass assignment protection off for this particular model and the way that you would do that is I will actually comment that line out and now let's add another protective and this one is called guarded guarded by default will guard every single field however if you set guarded to an empty array that essentially turns off mass assignment protection so that will actually turn it off for the entire model not for the entire application just for this particular model now let's try again and make sure that it still works hello again at service there we go so that is still working great so that's it those are the two ways that you can fix mass assignment one of them is a little bit more verbose which is that you actually have to type in every single field that you had say you had a date field and then you had another field you'll have to keep coming back to this file and keep adding things to it this is very protective way of doing it if you are not worried about that then you can actually just turn that off altogether so it's entirely up to you how you actually handle this but again just remember mass assignment exception just has to do with laravel protecting us from accidentally mass assigning a bunch of fields in your database and then creating a record in the database so with that we'll wrap it up for this lesson start to play around with adding some services in your application and when you get comfortable with that let's move on to the next episode
Info
Channel: Coder's Tape
Views: 45,985
Rating: undefined out of 5
Keywords: laravel 6, laravel mass assignment, laravel 6 tutorial, laravel 6 new features, laravel 6 advanced, laravel validation, laravel 6 validation, laravel validation rules, laravel validation error message, laravel validation tutorial, laravel request validation, laravel create post, laravel post request, laravel page expired, laravel page expired 419, laravel guarded, laravel fillable, laravel fillable vs guarded, laravel submit form, laravel form builder
Id: pJK_IeKSElY
Channel Id: undefined
Length: 25min 34sec (1534 seconds)
Published: Sun Sep 22 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.