Upload Method [Part 1]

Image Upload Service

In this video lesson we will be coding most of our Store Method of our controller. We will also setup the required Javascript that will tell DropzoneJS work the way we need it to work.

Video Information

Hi everyone, welcome back to Laracademy. It's mickey again and in this video we will be coding the upload method of our controller. We want to keep this method simple and small so we will be extracting some of the code into their respective libraries. Lets load up our IDE to get started.

First we will work in the store method. We are currently just returning the file back in the response. What we want to do instead is save the file.

// add namespace
use App\Models\Image;

// method content
public function store()
{
    $rules = [
      'file' => 'required|image',
    ];

    $this->validate(request(), $rules);

    if(request()->hasFile('file')) {
      if(request()->file('file')->isValid()) {
        // gather information
        $file = request()->file('file');
        $storageName = uniqid() .'.'. $file->extension();
        $originalName = $file->getClientOriginalName();

        // create the model
        $image = Image::create([
          'original_name' => $originalName,
          'storage_name' => $storageName,
        ]);

        $image->attachImage($file);

        return response([
          $image
        ], 200);
      }
    }

    return response([
      'responseText' => 'There was a problem uploading the file',
    ], 400);
}

Our next step will be to write some JavaScript so that dropzone will recognize our messages and also redirect when complete. So let's open uploads/create.blade.php.

<script>
        Dropzone.options.frmFile = {
            maxFiles: 1,
            init: function() {
                this.on('addedfile', function(file) {
                    $('#error').hide();
                });

                this.on('success', function(file, response) {
                    location.href = '/view/' + response.id;
                });

                this.on('error', function(file, errorMessage) {
                    $('#errorMessage').html(errorMessage.file[0]);
                    $('#error').show();

                     $(file.previewElement).find('.dz-error-message').text(errorMessage.file[0]);
                });
            }
        };
    </script>

Any finally we need to add the helper method to our Image model.

// helpers

public function attachItem($file)
{

}

Now we can load up Chrome and upload a few files and see what happens. In the end we should have some records in our database as well as being able to view the error message.

In the next lesson we are going to continue with the file uploads by getting the file to actually save. Thank you for watching.

Do you have a question? Go ahead and ask it below.

Please login to ask your question