Laravel 11 Drag and Drop File Upload with Dropzone JS

By Hardik Savani April 18, 2024 Category : Laravel

In this post, I would like to share with you how to drag and drop file upload using dropzone js in laravel 11 application.

Dropzone.js is a library for handling file uploads in web applications. It makes it easy to create a drag-and-drop interface where users can upload files by dragging them onto a designated area. It also provides features like file previews and progress indicators. With Dropzone.js, developers can enhance the user experience when dealing with file uploads on their websites or web apps.

In this example, we'll create an "images" table with "name," "filesize," and "path" columns. Then, we'll design a simple web page where users can drag and drop multiple images to upload. We will use Dropzone.js for drag and drop file upload. We'll save these images both to the "images" folder and the database. We will also show uploaded images on the Dropzone box.

Step for Laravel 11 Dropzone Drag and Drop Image Upload Example

  • Step 1: Install Laravel 11
  • Step 2: Create Migration and Model
  • Step 3: Create Controller
  • Step 4: Create Routes
  • Step 5: Create Blade File
  • Run Laravel App

So, let's follow the steps below to create drag and drop multiple image uploads in the Laravel 11 application example.

laravel 11 drag and drop images upload

Step 1: Install Laravel 11

This step is not required; however, if you have not created the Laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app

Step 2: Create Migration and Model

Here, we will create a migration for the "images" table. Let's run the below command and update the code.

php artisan make:migration create_images_table

database/migrations/2022_03_13_140040_create_images_table.php

<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('images', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('filesize');
            $table->string('path');
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('images');
    }
};

Next, run the create new migration using Laravel migration command as below:

php artisan migrate

Now we will create the Image model by using the following command:

php artisan make:model Image

app/Models/Image.php

<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class Image extends Model
{
    use HasFactory;
  
    protected $fillable = [
        'name', 'filesize', 'path'
    ];
}

Step 3: Create Controller

In this step, we will create a new `DropzoneController`. In this file, we will add two methods: `index()` and `store()`, for rendering views and storing images into a folder and implementing database logic.

Let's create the `DropzoneController` by using the following command:

php artisan make:controller DropzoneController

Next, let's update the following code to the Controller file.

app/Http/Controllers/DropzoneController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\JsonResponse;
use App\Models\Image;
 
class DropzoneController extends Controller
{
    /**
     * Generate Image upload View
     *
     * @return void
     */
    public function index(): View
    {
        $images = Image::all();
        return view('dropzone', compact('images'));
    }
      
    /**
     * Image Upload Code
     *
     * @return void
     */
    public function store(Request $request): JsonResponse
    {
        // Initialize an array to store image information
        $images = [];
  
        // Process each uploaded image
        foreach($request->file('files') as $image) {
            // Generate a unique name for the image
            $imageName = time() . '_' . uniqid() . '.' . $image->getClientOriginalExtension();
              
            // Move the image to the desired location
            $image->move(public_path('images'), $imageName);
  
            // Add image information to the array
            $images[] = [
                'name' => $imageName,
                'path' => asset('/images/'. $imageName),
                'filesize' => filesize(public_path('images/'.$imageName))
            ];
        }
  
        // Store images in the database using create method
        foreach ($images as $imageData) {
            Image::create($imageData);
        }
     
        return response()->json(['success'=>$images]);
    }
}

Step 4: Create Routes

Furthermore, open `routes/web.php` file and add the routes to manage GET and POST requests for rendering views and storing image logic.

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\DropzoneController;
  
Route::get('dropzone', [DropzoneController::class, 'index']);
Route::post('dropzone/store', [DropzoneController::class, 'store'])->name('dropzone.store');

Step 5: Create Blade File

At the last step, we need to create an "dropzone.blade.php" file. In this file, we will create a form with a file input button. So, copy the code below and paste it into that file.

resources/views/dropzone.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 11 Drag and Drop File Upload with Dropzone JS - ItSolutionStuff.com</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script src="https://unpkg.com/dropzone@6.0.0-beta.1/dist/dropzone-min.js"></script>
    <link href="https://unpkg.com/dropzone@6.0.0-beta.1/dist/dropzone.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
      .dz-preview .dz-image img{
        width: 100% !important;
        height: 100% !important;
        object-fit: cover;
      }
    </style>
</head>
<body>
    
<div class="container">
    <div class="card mt-5">
        <h3 class="card-header p-3">Laravel 11 Drag and Drop File Upload with Dropzone JS - ItSolutionStuff.com</h3>
        <div class="card-body">
            <form action="{{ route('dropzone.store') }}" method="post" enctype="multipart/form-data" id="image-upload" class="dropzone">
                @csrf
                <div>
                    <h4>Upload Multiple Image By Click On Box</h4>
                </div>
            </form>
            <button id="uploadFile" class="btn btn-success mt-1">Upload Images</button>
        </div>
    </div>
</div>
    
<script type="text/javascript">
  
        Dropzone.autoDiscover = false;

        var images = {{ Js::from($images) }};
  
        var myDropzone = new Dropzone(".dropzone", { 
            init: function() { 
                myDropzone = this;

                $.each(images, function(key,value) {
                    var mockFile = { name: value.name, size: value.filesize};
     
                    myDropzone.emit("addedfile", mockFile);
                    myDropzone.emit("thumbnail", mockFile, value.path);
                    myDropzone.emit("complete", mockFile);
          
                });
            },
           autoProcessQueue: false,
           paramName: "files",
           uploadMultiple: true,
           maxFilesize: 5,
           acceptedFiles: ".jpeg,.jpg,.png,.gif"
        });
      
        $('#uploadFile').click(function(){
           myDropzone.processQueue();
        });
  
</script>
    
</body>
</html>

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/dropzone

Output:

laravel 11 drag and drop multiple image output

I hope it can help you...

Shares