Laravel 11 Drag and Drop File Upload with Dropzone JS

Websolutionstuff | May-06-2024 | Categories : Laravel

Hello web developers! In this article, we'll see laravel 11 drag and drop file upload with dropzone js. Here, we'll upload files using drag and drop with Dropzone JS in laravel 11. Dropzone.js is one of the most popular drag and drop JavaScript libraries.

It is free, fully open source, and makes it easy for you to handle dropped files on your website. dropzone.js also provides a filter like we can make validation for max upload, a specific image or file extension, etc.

How to Create Drag and Drop File Upload in Laravel 11

laravel_11_drag_and_drop_file_upload

 

Step 1: Install Laravel 11 Application

In this step, we'll install the laravel 11 application using the following command.

composer create-project laravel/laravel example-app

 

Step 2: Create Migration and Model

Next, we'll create a migration for the images table using the following command.

php artisan make:migration create_images_table

Migration:

<?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');
    }
};

Then, migrate the table into the database using the following command.

php artisan migrate

Then, we'll create the Image model 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

Next, we'll create a new DropzoneController.php using the following command.

php artisan make:controller DropzoneController

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
    {
        $images = [];
  
        foreach($request->file('files') as $image) {
            $imageName = time() . '_' . uniqid() . '.' . $image->getClientOriginalExtension();
              
            $image->move(public_path('images'), $imageName);
  
            $images[] = [
                'name' => $imageName,
                'path' => asset('/images/'. $imageName),
                'filesize' => filesize(public_path('images/'.$imageName))
            ];
        }
  
        foreach ($images as $imageData) {
            Image::create($imageData);
        }
     
        return response()->json(['success'=>$images]);
    }
}

 

Step 4: Define a Routes

Then, define the routes into the web.php file.

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

Now, we'll create a dropzone.blade.php file. we'll create a form with a file input button.

resources/views/dropzone.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>How to Create Drag and Drop File Upload in Laravel 11 with Dropzone JS - Techsolutionstuff</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/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/[email protected]/dist/dropzone-min.js"></script>
    <link href="https://unpkg.com/[email protected]/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">How to Create Drag and Drop File Upload in Laravel 11 with Dropzone JS - Techsolutionstuff</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>

 

Step 6: Run the Laravel 11 Application

Now, run the laravel 11 application using the following command.

php artisan serve

Output:

Dropzone JS Laravel 11

 


You might also like:

Recommended Post
Featured Post
How To Get Current URL In React JS
How To Get Current URL In Reac...

As a React JS developer, I have come to appreciate the power and popularity of this remarkable JavaScript library. Its c...

Read More

Aug-09-2023

Paypal Payment Gateway Integration In Laravel 8
Paypal Payment Gateway Integra...

In this tutorial, we will see paypal payment gateway integration in laravel 8. Paypal is an international payment p...

Read More

Jan-10-2022

How to Multiple Image Upload in Laravel 10 API
How to Multiple Image Upload i...

Hello everyone! I'm excited to share with you how I'm enhancing my Laravel 10 API by enabling the capability to...

Read More

Dec-01-2023

How To Generate QR Code In Angular 13
How To Generate QR Code In Ang...

In this article, we will see how to generate QR code in angular 13. In this example, we will use the angularx-qrcod...

Read More

Jun-09-2022