Laravel Image Upload using Dropzone Tutorial Example

Laravel 9 Dropzone Image Upload Example; In this tutorial we will show you how to upload multiple images / files using Dropzone in laravel application. This quick guide will help you step by step drag and drop multiple file upload with dropzone js and preview and store to database.

Dropzone is a jQuery library, Through which we drag and drop the file and save it in our database. Its not a though but need to attention for the code, you just need to add dropzone js and css cdn in your laravel project. Dropzone.js also provide filter like we can make validation for max upload, specific image or file extension etc.

Uploading image or file with dropzone in Laravel is no more going to be a difficult task. I am going to share how does Laravel dropzone file upload functionality is made from scratch.

Let’s start for working with Multiple images upload using dropzone in laravel 5, laravel 6, laravel 7, laravel 8 or laravel 9 app.

Laravel 9 Dropzone Image Upload Example

Following the following step for Laravel Dropzone example to Drag and Drop File/image Upload in Laravel apps;

  • Step 1 – Download Laravel App
  • Step 2 – Connect Database to App
  • Step 3 – Create Model & Migration
  • Step 4 – Add Routes
  • Step 5 – Create Blade View
  • Step 6 – Setup Dropzone in Laravel
  • Step 7 – Create Controller
  • Step 8 – Dropzone remove file from Database
  • Step 9 – Run Development Server

Step 1: Downlload Laravel App

First of all, download or install laravel new laravel app setup. So, open terminal and type the following command to install new laravel app into your machine:

composer create-project --prefer-dist laravel/laravel laraveldropzone

Go inside the app:

cd laraveldropzone

Step 2: Connect Database to App

Open the .env file and add your database credentials such as database name, username equally important password:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_dropzone
DB_USERNAME=root
DB_PASSWORD=

Step 3: Create Model & Migration

Now geration model and migration files your need to run the following command in your terminal.

php artisan make:model File -m

It will create two files.

  • File.php model.
  • create_files_table migration file.

Now open your migration file database\migrations\2020_04_26_070731_create_files_table.php and put the below code.

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateFilesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('files', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name')->nullable();
            $table->string('path')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('files');
    }
}

Now run the migrate command to generate a table in your database.

php artisan migrate

Step 4: Add Routes

Open your routes\web.php file and add three routes on it. One for showing the dropzone form, 2nd is storing the file in database and another is remove file from database.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\FileController;

Route::get('files', [FileController::class, 'index' ]);
Route::post('files', [FileController::class, 'store' ])->name('file.store');
Route::post('files/remove', [FileController::class, 'remvoeFile' ])->name('file.remove');

Step 5: Create a Blade file

Now you need to create a blade file named as files.blade.php to showing the dropzone where you can drag and drop your files and save the database.

So open the new created blade file resources\views\files.blade.php and put the below code on it:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <title>Laravel Multiple Files Upload Using Dropzone with - CodingDriver</title>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.7.0/min/dropzone.min.css">

</head>
  <style>
  .alert-message {
    color: red;
  }
</style>
<body>

<div class="container">
    <h2 style="margin-top: 12px;" class="alert alert-success">Laravel Multiple Files Upload Using Dropzone -
       <a href="https://www.codingdriver.com" target="_blank" >CodingDriver</a>
     </h2>
    <div class="row" style="clear: both;margin-top: 18px;">
        <div class="col-12">
          <div class="dropzone" id="file-dropzone"></div>
        </div>
    </div>
</div>
</body>
</html>

Step 6: Setup Dropzone

Now add the follow code in your js file or add in your files.blade.php file a closing body div.

<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.7.0/min/dropzone.min.js"></script>

<script>
  Dropzone.options.fileDropzone = {
    url: '{{ route('file.store') }}',
    acceptedFiles: ".jpeg,.jpg,.png,.gif",
    addRemoveLinks: true,
    maxFilesize: 8,
    headers: {
    'X-CSRF-TOKEN': "{{ csrf_token() }}"
    },
    removedfile: function(file)
    {
      var name = file.upload.filename;
      $.ajax({
        type: 'POST',
        url: '{{ route('file.remove') }}',
        data: { "_token": "{{ csrf_token() }}", name: name},
        success: function (data){
            console.log("File has been successfully removed!!");
        },
        error: function(e) {
            console.log(e);
        }});
        var fileRef;
        return (fileRef = file.previewElement) != null ?
        fileRef.parentNode.removeChild(file.previewElement) : void 0;
    },
    success: function (file, response) {
      console.log(file);
    },
  }
</script>

Step 7: Create Controller

A controller holds the logic to handle the drag and drop file upload, so go ahead and generate a new controller:

php artisan make:controller FileController

Next, open app\Http\Controllers\FileController.php file and update the below code on it.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\File;

class FileController extends Controller
{
    public function index()
    {

      return view('files');
    }

    public function store(Request $request)
    {
      $file = new File;

      if ($request->file('file')) {
        $filePath = $request->file('file');
        $fileName = $filePath->getClientOriginalName();
        $path = $request->file('file')->storeAs('uploads', $fileName, 'public');
      }

      $file->name = $fileName;
      $file->path = '/storage/'.$path;
      $file->save();

      return response()->json([ 'success' => $fileName ]);
    }

}

Step 8: Remove file From Database

Add below code in your controller to removing the file from database

    public function remvoeFile(Request $request)
    {
        $name =  $request->get('name');
        File::where(['name' => $name])->delete();

        return $name;
    }

Step 9: Run Development Server

Last step, open command prompt and run the following command to start developement server:

php artisan serve

Then open your browser and hit the following url on it:

http://127.0.0.1:8000/files

So, Laravel Image Upload using Dropzone Tutorial Example tutorial is complted now. I hope its work for you.. If you got any errors please comment us for more follow us on social networks.

4 thoughts on “Laravel Image Upload using Dropzone Tutorial Example”

Leave a Comment