Now that we have a form, we need to be able to validate that the data a user enters is well formed. In this lesson, I’ll show you how Laravel makes input validation a breeze with its simple and intuitive validation library.
1.Introduction2 lessons, 04:03
2.Laravel Website Basics3 lessons, 11:34
3.Create a Contact Page3 lessons, 22:34
4.Conclusion1 lesson, 02:44
Right, so we have our simple form ready to go. The next step is being able to actually submit the form and validate that the data the user has entered is what we expect. This is very important. And its a crucial step. Because we should never ever trust user input. So, we always validate. And if you are storing the data, you should always sanitize. This is one of the most important things you will ever do when building a website or an application. So that we can handle the submission of our form, we're going to need another route. In our web route file, we will wire one up. Except this time, we are not going to be using a get. We are going to be needing a post. If you remember, when we set up the form. We set the method on the form to post. So we need a post route so that we can handle the request. The route, itself, is going to be for the exact same URI. And we are going to be giving this route a name. So we will open up an array and add the as key. For this route, we are going to name it contact.submit. Now you will remember that last time, we decided to name the form contact.form. So this one, once again, describes what the route does. So that we can easily identify it. So we are now going to need to pass in the closure. Which is where we are going to handle the form submission. For now, let's dump out our request data. And to do this, we're going to use the DD helper function. We need to pass in request input as the only argument. What this will do is dump out all of the request input for us, so that we can inspect it and kill the execution of the script. We now need to make sure that our form submits to this new route by going back to our form view. In our form tag, we will set the action attribute to the post route that we just created. Once again, we can use the route help function with contact.submit as the name. Before we can go and test this out, there is one more thing that we need to add to our form. And it is going to be the CSRF token. CSRF, or cross-site request forgery, can be quite scary. But luckily for us, Laravel has built in protection that we can utilize. Essentially, on each request, Laravel would generate and store a token. And when a form is submitted, it looks for that token in the submitted data. If it can't find the token or the token is invalid. Then it will prevent the form from submitting. So adding the token to our form is actually quite simple. After the opening form tag, we will use the curly braces and call the CSRF underscore field helper function. What this does is it generates the required hidden form tag with the correct name. And the CSRF token as the value. It is important that you add this token to all of your forms. Either that, or you would disable CSRF protection. But you would only do that when you really know what you are doing and why you need to disable it. I always recommend that you keep this on and simply add in the token to your forms. Right, so now we can check out what we have so far. What we should see is all of our input data dumped out to our browser once we hit the Submit button. So let's try it out. In the form, we'll just enter some dummy data so that we can see what happens. Then, when we hit submit, we can see that the same data has been dumped out. Including the hidden CSRF token that we just looked at. So that is all well and good, as it means our form is working. So we should now be able to validate the data. Validation in Laravel is very easy, thanks to its powerful validation library. All we need to do is define some rules for our inputs. And then feed that and our data to the validator. It will then return either true or false, depending on whether or not validation succeeded. And if a validation did fail, we would be able to get all of the errors. And with those errors, we would be able to redirect back to the form. And then show the errors to the user. So in our web routes file, we'll use the validator helper function to create a new validator instance. This function takes several arguments. The first is the data that we wish to have validated for us. That's going to be request input. Now we could also limit this to only the data that we want. So let's do that instead. We are going to be using the only method instead of the input method. And we will give this method the names of each of the inputs in our form. So we have name, email and message. And now we are only going to pull those inputs from the data. This is very handy when you only want to pull and validate a few things. Or if you want to explicitly define the data that you expect, which I always recommend. The second argument to the validator function is the rules that we wish to use on our data. This argument needs to be an array, where the keys are the names of our input fields.So to start with, we'll have the name key. For the value, we can do one of two things. First, we can use an array, and pass in each rule as a value. For the name, we only have one rule. And it needs to be required. If you don't want to use an array, then you can use a pipe delimited string. And to define another rule, you just do a pipe followed by the second rule and so on and so forth. Our next input field that we need to validate is the sender's email. So the key will be email. And we are going to need a couple of rules for this one. First, we want the email to be required. And then we want to use the email rule to also validate that it is a valid email format. Note that this rule doesn't actually determine if the email exists. It merely looks at the format. So if the email that they enter is missing, the at symbol, then it's not a valid email. And this row will fail. Lastly, we have our message input field. And for this one, we want it to be required, and that is all we need. Remember that there are a heap of validation rules available. And you can also create your own, should you need even more flexible validation. So now that we have our input data and our validation rules. The remaining arguments to the validator function are required. But we could pass in some custom error messages or some custom attributes. We are not going to need to worry about any of those, though. We are now set to validate our data. All we need to do is open up an if statement, and check if the validation passes, simple. If it does, then we'll use the DD helper function to dump out. And we'll say, hooray, it passed. Outside of the if, we can safely assume that validation has failed. So again, we use the DD helper function. Except, this time, we will dump out validation errors. And this should dump out an errors object if we encountered any. So now it is time to test this out. If we refresh our form and then submit it without any data. We will see that we have a MessageBag object dumped out. And we can see the errors that we encountered. All of our required inputs were empty, so the validation has failed, excellent. And if we now go back and add some dummy data and try again. We will be able to pass the validation, and we will see the success message. So now that we have got it validating, we need to clean it up a little bit. Instead of dumping out the errors, we are going to need to redirect back to our form and display them. Sound a bit hard? It might, but it is actually really easy. In our routes file, we need to replace the dump with a return. What we are going to do is return a redirect. And then we will chain a call to the route method. Does this look familiar? It should, because it works exactly the same as the route helper function that we have already used. All we need to do is give it the name of our route that we wish to redirect to, which, for us, is contact.form. But we are not quite done yet. We can now chain another method, called with errors. And this method takes a single argument which is the errors object that we dumped out before. So if we read it back, we want to redirect to the route named contact.form. And we want to redirect there with the errors from our validator. What this will do is flash the errors message bag object to the session. Which means it will only be available on the next request. And then it will be destroyed. It is simple enough, really. All we need to do now is actually modify our contact view so that we can display the errors. Above our form, we are going to open up an if statement where we will check if there are any errors. And now, you might be wondering, where did this errors variable come from? Well, before rendering any views. Laravel will automatically check to see if any errors have been flashed to the session. And if there was, it will automatically bind them to this errors variable. And if there were no errors, then it simply creates a new message bag instance. And sets it as the errors variable. This means that we can always use this errors variable in our views, and expect it to be a message bag object. Where it will either have errors or it will be empty. So if there are errors, then we want to display them. So we will just open up an unordered list. And then we can use a foreach loop to spin through all of the errors. Inside the foreach, we will use a list item to display each of the errors individually. So let's try this out. In our web browser, we will refresh our form. And then we will submit it with no data. Instantly, we will be redirected back to the form, where we can see the errors are displayed at the top. So what if we enter a valid email, and then we submit with no other data? Of course, we are going to be redirected back. But the email that we entered is no longer there. And that's not very good for the user. Wouldn't that be nice if we could reuse the old data that the user submitted so they didn't have to reenter it each time? Well, luckily for us, this is really easy as well. If we go back to our contact view, we can provide a value attribute to each of our inputs. For the value, we're going to use the old helper function, which pulls in old input from Flash session data. All we need to do is provide the name of the input to the function. And if we wanted, we could provide a default value as the second argument. Which is very helpful when you are editing models, for example. And you can pass in the database value. So now, in our routes file, we do need to chain one more method to the returned redirect. And that's the with input method. So back in our browser, we can once again enter a valid email. And then we will hit, submit. We will be redirected back once more. But this time, our email address that we entered will still be in the input. Which means that we can simply edit it instead of having to reenter. And that is a lot smoother for the end user experience. Great, so now we are validating our input. And that is all there is for this lesson. In our final lesson, we are going to look how we can actually send out the email from this contact form.