The last important piece of this puzzle is the blade template, which will contain all the HTML, CSS, and javascript for our simple application. Here’s the code – I’ll explain later.

   <h1> Upload a file </h1>
   <form id = "uploadForm" name = "uploadForm" action = "{{route ('upload')}}" enctype = "multipart / form-data">
       <label for = "fileName"> File Name: </label>
       <input type = "text" name = "fileName" id = "fileName" required /> <br />
       <label for = "userFile"> Select a File </label>
       <input type = "file" name = "userFile" id = "userFile" required />
       <button type = "submit" name = "submit"> Submit </button>
   <h2 id = "success" style = "color: green; display: none"> Successfully uploaded file </h2>
   <h2 id = "error" style = "color: red; display: none"> Error Submitting File </h2>
   <script src = "//"> </script>
        $ ('# uploadForm'). on ('submit', function (e) {
            e.preventDefault ();
            var form = $ (this);
            var url = form.attr ('action');
            $ .ajax ({
                url: url,
                type: "POST",
                data: new FormData (this),
                processData: false,
                contentType: false,
                dataType: "JSON",
                success: function (data) {
                    $ ("# fileName"). val ("");
                    $ ("# userFile"). val ("");
            }). done (function () {
                $ ('# success'). css ('display', 'block');
                window.setTimeout (() => ($ ("# success"). css ('display', 'none')), 5000);
            }). fail (function () {
                $ ('# error'). css ('display', 'block');
                window.setTimeout (() => ($ ("# error"). css ('display', 'none')), 5000);

This is what our download page looks like :

This is a very typical example of a blade file containing an HTML form and javascript / jQuery to add asynchronous functionality (so the page doesn’t refresh). There is a basic <form> tag with no method attribute (which I’ll explain in a second) and a curious action attribute with the value {{route (‘file.upload’)}}. In the blade, this is what is known as a directive. The directive is just a fancy name for a function – these are functions specific to blade templates that perform various operations that are common to building web pages and web applications. For a better understanding of all the cool shit a blade can do . In the above case, we are using the route directive to generate the URL for submitting the form.

Remember that we defined our routes earlier in the application inside the web.php file, providing an easy-to-remember name for each one. The {{route ()}} directive takes the name of a route, looks for it in the list of internal cached routes and generates a full URL based on the definition of that route in the web.php file. In this first case, we are specifying that we want the form to submit its submitted data to our application’s / process URL, which is defined as a POST route.

The next weird thing you might have noticed is the @csrf tag just below the opening form tag. In the blade, this tag generates a _token parameter on the form, which is validated internally by the application before the form data is allowed to be processed. This ensures that the data inside the form is of valid origin and prevents cross-site-request-spoofing attacks.

After that we define our form as normal, however, note that the names of our form parameters, userFile and fileName, are exactly the same as defined inside our request object. If we forgot to include the input for a given parameter that was defined in the request object (or wrote it incorrectly), the request would fail and return an error preventing the original form request from reaching the controller method located at UploadController @ process.

Try it and submit some files to your application using this form. After that go to the / list page to see the contents of the download folder, and the files you downloaded are listed in the table:

Big picture

Let’s take a step back and see what we’ve done.

This diagram depicts the application as it is now (high-level details excluded):

You must remember that the request object we created at the beginning of this lesson must have the same parameters defined in its rules method as in the form in the blade template (unless you reread the section on Creating validation logic). The user enters a form on a web page that is rendered using the blades templating engine (this process is of course done on autopilot so we don’t even need to think about it) and submits the form. The jQuery template code at the bottom stops the default submission (which automatically redirects to a separate page), creates an ajax request, loads the request with the form data and uploads the file and sends it all to the first layer of our Application: request.

The request object is populated by binding parameters within the rules () method to the submitted form parameters, and then validating the data against each specified rule. If all the rules are satisfied, the request is passed to any controller method that matches the values ​​defined in the web.php route file. In this case, it’s the process () method of UploadController that does the work. After we get into the controller, we already know that the request passed validation, so we don’t need to re-check if the given filename is actually a string or a userFile parameter, actually contains some type of file … We can continue as usually.

The controller method then extracts the validated parameters from the request object, generates the fully qualified filename by concatenating the passed fileName parameter with the original userFile extension, stores the file in a directory in our application, then returns a simple JSON-encoded response confirming that the request was successful. The answer comes from jQuery logic, which performs a few more UI related tasks such as displaying a success (or error) message for 5 seconds, then hiding it, and clearing previous form entries … this is so User knows for sure that the request is was successful, and can download another file if desired.

Also notice the diagram above where the line goes between client and server. This concept is absolutely essential to understand and will help you solve problems and problems that may arise in the future when juggling, such as multiple asynchronous requests that may arise at any given time. The split happens right at the border of the request object. The request object itself can be thought of as a “gateway” to the rest of the application … It does the initial validation and registration of form values ​​submitted from the web browser. If they are considered valid, then this continues to the controller. Everything before that is at the forefront (“client” literally means “on the user’s computer”). The response is returned from the application back to the client side,

Leave a Reply

Your email address will not be published. Required fields are marked *

Leave a Reply

Your email address will not be published. Required fields are marked *