Laravel 9 - Dropzone.js How to drag and drop / upload multiple images
Laravel 9 - Dropzone.js How to drag and drop / upload multiple images
In this tutorial, we’ll cover how to drag and drop or upload multiple images in Laravel 9 using Dropzone, making file uploads easier with a simple interface.
If you're a video person, feel free to skip the post and check out the video instead!
Quick Overview
In this guide, we walk through integrating Dropzone.js into a Laravel 9 application to handle drag-and-drop image uploads. We begin by setting up a fresh Laravel project, followed by creating the necessary model, migration, and controller for managing image data. Then, we design a Blade view using Dropzone’s UI for a smooth upload experience. Routes are defined to display the upload form and process the uploaded files. Inside the controller, we validate and save each image both to the public/image directory and the database. Finally, we test the functionality by launching the Laravel dev server and uploading images through the Dropzone interface. If everything is configured properly, the images should be uploaded successfully and stored with ease.
Step # 1 : Set Up a Fresh Laravel 9 Project.
To begin integrating Dropzone.js, start by creating a new Laravel 9 project. If Laravel is installed globally, use the following command.
laravel new dropzone
Alternatively, you can use Composer.
composer create-project laravel/laravel --prefer-dist dropzone
Running either command will generate a fresh Laravel project with all the required files and directory structure. Once done, your development environment is ready for Dropzone.js integration and front-end setup.
Step # 2 : Access the Project.
Open your terminal (e.g., Git Bash) and navigate to the root directory of your Laravel project. For example.
cd c:xampp/htdocs/dropzone
Make sure you’re in the correct project folder before proceeding with the next steps.
Step # 3 : Create Model, Migration & Controller for Images.
To manage image uploads, generate a model, migration, and controller in one command using Artisan.
php artisan make:model Image -cm
This will create an Image model, a corresponding migration file for the database table, and an ImageController. You’ll use these to handle image storage, database interaction, and request logic.
Step # 4 : Add Columns to the Images Table.
Open the generated create_images_table migration file and define the necessary columns. We’ll store just the image filename for now.
public function up(): void
{
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
Next, open the Image model and define which fields are mass assignable by adding the $fillable property. This is important if you're inserting data through forms or controller methods.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
use HasFactory;
protected $fillable = [
'name',
];
}
After updating the migration and model, run the following command to apply the changes to your database.
php artisan migrate
This will create the images table with the specified structure in your database.
Step # 5 : Create a View for Dropzone Upload.
Next, let’s build the Blade view that contains the upload form and Dropzone.js integration. Create a new file named dropzone.blade.php (Path: resources/views/dropzone.blade.php). Paste the following HTML content into the file.
<!DOCTYPE html>
<html>
<head>
<title>Laravel 9 Dropzone JS - Code Shotcut</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://unpkg.com/dropzone@5/dist/min/dropzone.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/dropzone@5/dist/min/dropzone.min.css" type="text/css" />
</head>
<body>
<div class="container">
<div class="row mt-5">
<div class="col-md-12">
<h1>Laravel 9 Dropzone JS example - Code Shotcut</h1>
<form action="{{ url('/upload-images') }}" method="post" enctype="multipart/form-data" id="images" class="dropzone">
@csrf
<div>
<h4 class="text-center">Upload or Drag & Drop images</h4>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
Dropzone.autoDiscover = false;
var dropzone = new Dropzone('#images', {
thumbnailWidth: 200,
maxFilesize: 2, // in MB
paramName: "images[]",
acceptedFiles: ".jpeg,.jpg,.png,.gif",
error: function(file, errorMessage) {
errors = true;
},
queuecomplete: function() {
var count = dropzone.files.length;
setTimeout(function () {
dropzone.removeAllFiles();
alert(count == 1 ? "Image uploaded successfully" : "Images uploaded successfully");
}, 1000);
}
});
</script>
</body>
</html>
The enctype="multipart/form-data" attribute ensures that uploaded images are correctly processed by the server. Since we’re using Dropzone, there’s no need to include a traditional <input type="file">—the class="dropzone" on the <form> element takes care of that automatically. Additionally, the id="images" allows us to manually initialize the Dropzone instance using JavaScript, giving more control over behavior and validation. This view sets up the visual and functional part of the upload system using Dropzone’s drag-and-drop interface.
Step # 6 : Create routes.
Open your web.php file located in the routes directory and start by importing the ImageController class using.
use App\Http\Controllers\ImageController;
Next, define two routes, one for displaying the upload view and another for handling the uploaded images. Add the following lines.
Route::get('/upload', [ImageController::class, 'index']);
Route::post('/upload-images', [ImageController::class, 'store']);
These routes will direct the user to the Dropzone upload page and handle the image upload functionality respectively.
Step # 7 : Create methods in the ImageController.
Access ImageController and create two methods. One for showing the form and another for handling the image upload.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Image;
class ImageController extends Controller
{
public function index()
{
//Return view
return view('dropzone');
}
public function store(Request $request)
{
//Validate and upload images
$request->validate([
'images.*' => 'required|mimes:png,gif,jpg,bim|max:2048',
]);
if($request->images)
{
foreach ($request->images as $image) {
$modifiedImage = time() . ' - ' . $image->getClientOriginalName();
$image->move(public_path('/image'), $modifiedImage);
Image::create([
'name' => $modifiedImage,
]);
}
}
return back()->with('success', 'images uploaded successfully.');
}
}
The index method loads the upload form, while the store method handles the entire image upload process. It first validates the incoming files to ensure they meet the required format and size constraints. If valid images are found, each one is renamed with a timestamp to avoid filename conflicts, moved to the public/image directory, and its name is saved to the database using the Image model. This ensures both proper file storage and easy retrieval later. After the upload is complete, the method redirects back with a success message, confirming that the images were processed and saved correctly.
Step # 8 : It's time to test.
Start the Laravel development server using the command below.
php artisan server
Once the server is running, visit the URL http://127.0.0.1:8000/upload in your browser. You should see the Dropzone form. Try dragging and dropping or selecting images to test the upload functionality. If everything is set up correctly, your images will be uploaded and saved in the public/image folder and their names will be stored in the database.
Conclusion
By following this step-by-step guide, you’ve successfully integrated Dropzone.js into your Laravel 9 application to enable seamless drag-and-drop image uploads. From setting up a fresh Laravel project to creating models, migrations, controllers, and a custom Blade view, you’ve built a complete upload system with both front-end and back-end functionality. The images are now stored in the public/image folder and recorded in the database, making it easy to manage and retrieve them later. This setup offers a solid foundation for handling file uploads in a user-friendly way. As your project evolves, you can expand this functionality with features like image previews, deletion, or cloud storage integration.
For additional customization and options, refer to the official Dropzone.js documentation.
Share this with friends!
To engage in commentary, kindly proceed by logging in or registering
Subscribe to Our Newsletter
Stay ahead of the curve! Join our newsletter to see what everyone’s talking about.
0 Comments