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
The Mix Manifest Does Not Exist Laravel
The Mix Manifest Does Not Exis...

In this article, we will see the mix manifest does not exist in laravel 8 and laravel 9. We will solve the mix...

Read More

Oct-28-2022

How To Get Children Element In jQuery
How To Get Children Element In...

In this article, we will see how to get the children of this selector in jquery. You can use the find() method...

Read More

Jul-13-2022

How to Search Object by ID and Remove It from JSON Array In JavaScript
How to Search Object by ID and...

In this example we will see how to search object by id and remove it from json array in javascript. we need to add ...

Read More

May-26-2021

Laravel 9 Order By Query Example
Laravel 9 Order By Query Examp...

In this article, we will see laravel 9 order by query example. how to use order by in laravel 9.The orderBy me...

Read More

Mar-28-2022