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
Laravel 8 Datatables Filter with Dropdown
Laravel 8 Datatables Filter wi...

In this example we will see laravel 8 datatables filter with dropdown, Here we will add datatables custom...

Read More

Jun-16-2021

Laravel 8 Send Mail using Queue
Laravel 8 Send Mail using Queu...

In this tutorial I will show you laravel 8 send mail using queue, many time we can see some process to take mo...

Read More

Sep-24-2021

Laravel 11 Install Yajra Datatable Example
Laravel 11 Install Yajra Datat...

In this tutorial, we'll explore an example of installing Yajra Datatable in Laravel 11. In every project, it's e...

Read More

Apr-10-2024

Laravel 8 Export Buttons In Datatables Example
Laravel 8 Export Buttons In Da...

In this article, we will see an example of laravel 8 export buttons in datatables. If you want to export data...

Read More

Oct-14-2020