In this post, you are going to learn how to drag and drop file upload using Dropzone Js in Laravel application. the version of Laravel used in this tutorial is 11.
Dropzone.js is an open source library that provides beautiful and easy to use drag’n’drop file uploads with image previews.
In this example, we’ll create a “files” 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. The images will stored in the “images” folder and in the files database table. We will also show uploaded images on the Dropzone box.
Follow the step by step guide below.
Step 1: Install Laravel
This step is not compulsory; but, if you have not created the Laravel app, then you may go ahead and execute the below command:
composer create-project laravel/laravel example-project
Step 2: Create Migration and Model
Here, we will create a migration for the “files” table. Let’s run the below command and update the code.
php artisan make:migration create_files_table
database/migrations/2024_05_06_221200_create_files_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('files', 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('files');
}
};
Next, run the create new migration using Laravel migration command as below:
php artisan migrate
Now we will create the File model by using the following command:
php artisan make:model File
Update the File model as displayed below:
app/Models/File.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class File 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: `form()` for rendering views and `store()` for 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.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\File;
class DropzoneController extends Controller
{
public function form()
{
$images = File::all();
return view('dropzone', compact('images'));
}
public function store(Request $request)
{
// Initialize an array to store image information
$images = [];
// Process each uploaded image
foreach ($request->files as $file) {
// Generate a unique name for the image
$imageName = time() . '_' . uniqid() . '.' . $file->getClientOriginalExtension();
// Move the image to the desired location
$file->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) {
File::create($imageData);
}
return response()->json(['success' => $images]);
}
}
Step 4: Create Routes
In this step, open `routes/web.php` file and add the routes to manage GET and POST requests for rendering views and storing image logic.
Route::get('dropzone-form', [DropzoneController::class, 'form']);
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 - Drag and Drop File Upload with Dropzone JS - techbly.ng</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 Drag and Drop File Upload with Dropzone JS - techbly.ng</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-form

