- This topic has 0 replies, 1 voice, and was last updated 1 year, 1 month ago by
Tochukwu.
- AuthorPosts
- November 27, 2019 at 5:43 pm #81208Participant@tochukwu
Some time ago I was faced with the challenge of creating a field that accepts multiple files during registration while working for a client and ‘multiple input field’ wasn’t an option because each application comes with different unpredictable numbers of files. This led me into a search for a better option and DropzoneJs saved the day. So in this tutorial, we will be learning how to store and delete multiple files in a Laravel framework using DropzoneJs library.
Laravel is an open-source PHP framework and it is the most used PHP framework for building robust web applications, this is due to its simple features and high performance.
For a proper understanding of this tutorial, a DropzoneJS is a JavaScript open-source library that allows users to drag and drop files with preview. For more details, you can visit DropzoneJs website. Click on this link to go to the website.
This tutorial will be made as explicit as possible in order to make it beneficial to all levels of PHP developers including beginners. To avoid getting stuck it is imperative to follow the instructions on this tutorial step by step but modifications can be made where necessary to suit your application, some of which will be mentioned below.
Step 1
To start open your terminal and type the command below.
Laravel new project-name
Or
composer create-project laravel/laravel project-name
The above command will install a new Laravel project into the directory you specified and get you started. Proceed to set up your database after installation. For this tutorial, we will be using MySQL database.
Your
.env
file should look like this:1234567891011121314PP_NAME=LaravelAPP_ENV=localAPP_KEY=base64:***********************************APP_DEBUG=trueAPP_URL=http://localhostLOG_CHANNEL=stackDB_CONNECTION=mysqlDB_HOST=127.0.0.1DB_PORT=****DB_DATABASE=files-dropzoneDB_USERNAME=DB_PASSWORD=Go to your terminal or command prompt and CD (change directory) into your Laravel project folder and enter the command
php artisan serve
to start your local server.Step 2
Then create your migration (means to create a table in your database). We will be using the command below to create the model controller and migration.
php artisan make:model Dropzone -mcr
Where ‘mcr’ means:
m – migration. For the database schema.
c – controller. The functions will be written here.
r – resources for routing.You have the option of giving your files another name that differs from mine.
Paste the code below in your
database/migration/…create_dropzones_table.php
123456789101112131415161718192021222324252627282930313233<?phpuse Illuminate\Database\Migrations\Migration;use Illuminate\Database\Schema\Blueprint;use Illuminate\Support\Facades\Schema;class CreateDropzonesTable extends Migration{/*** Run the migrations.** @return void*/public function up(){Schema::create('dropzones', function (Blueprint $table) {$table->bigIncrements('id');$table->string('name');$table->string('file_path');$table->timestamps();});}/*** Reverse the migrations.** @return void*/public function down(){Schema::dropIfExists('dropzones');}}After pasting the code above, enter the command
php artisan migrate
to create a table in your database.After migration your table should look like the image above.
Step 3
Now create three blades. First blade for links, second for the dropzone form and third to display the files.
You can either download the dropzone folder into your project and include the link on your page or use the CDN (content delivery network) link. For this tutorial, I will be using the CDN. This is to make the page load faster.
Here’s the link to the dropzone CDN.
Your first blade should look like the code below.
NB: The bootstrap CDN is to give the form a fine structure.
resources/views/master.blade.php
1234567891011121314151617<!DOCTYPE html><html><head><title>Dropzone in Laravel</title><link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"/><link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/dropzone.css"/></head><body><div class="container">@yield('content')</div><script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script><script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/dropzone.js"></script></body></html>In your second blade create a form element and include the dropzone class in your form.
resources/views/form.blade.php
1234567891011121314@extends('master')@section('title', 'Form')@section('content')<form method="POST" action="{{ route('save.files') }}" enctype="multipart/form-data" class="dropzone" id="dropzone">@csrf</form><br /><center><a href="{{ route('view.files') }}" rel="nofollow">Files</a></center>@stopIf you are using Laravel Collective for HTML your form element should look like this:
123{!! Form::open(['method' => 'post', 'action' => 'DropzoneController@store, 'files' => true, 'class' => 'dropzone', 'id' => 'dropzone' ]) !!}....{!! Form::close() !!}The third blade will display the files stored in the database.
resources/views/files.blade.php
123456789101112131415161718192021222324252627282930@extends('master')@section('title', 'Files')@section('content')<div class="row">@foreach($allfiles as $allfile)<div class="col-md-4"><div class="card" style="width: 18rem;"><img src="{{ url($allfile-/>file_path) }}" class="card-img-top" alt="..."><div class="card-body"><h5 class="card-title">Lorem Ipsum</h5><p class="card-text">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip.</p><form action="{{ route('delete.file', [$allfile->id]) }}" method="POST">@csrf{{ method_field('DELETE') }}<button type="submit" class="btn btn-primary">Delete</button></form></div></div></div>@endforeach</div><br /><form action="{{ route('delete.all') }}" method="POST">@csrf{{ method_field('DELETE') }}<button type="submit" class="btn btn-primary">Delete All</button></form>@stopWe will use the
foreach()
loop to iterate through the values.Step 4
At this stage, we will be creating our routes. In Laravel, all routes are defined inside the route folder.
routes/web.php
12345678Route::get('/form', function () {return view('form');});Route::post('/upload-files', 'DropzoneController@store')->name('save.files');Route::get('/view-files', 'DropzoneController@viewFiles')->name('view.files');Route::delete('/delete-file/{id}', 'DropzoneController@destroyFile')->name('delete.file');Route::delete('/delete-all', 'DropzoneController@destroyAll')->name('delete.all');If you are correctly following this tutorial step by step, then at this stage your form should look like the image below if you run your application. If your form is looking like the image below then proceed to the next step but if not then go back and check where you are missing it.
Step 5
Now create these functions in your controller.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667<?phpnamespace App\Http\Controllers;use App\Dropzone;use Illuminate\Http\Request;class DropzoneController extends Controller{/*** Display a listing of the resource.** @return \Illuminate\Http\Response*/public function viewFiles(){$allfiles = Dropzone::all();return view('files', compact('allfiles'));}/*** Store a newly created resource in storage.** @param \Illuminate\Http\Request $request* @return \Illuminate\Http\Response*/public function store(Request $request){$files = $request->file('file');//$request->file('file')->move(public_path() . '/public/images/');$imageName = $files->getClientOriginalName();$files->move(public_path('images'), $imageName);$filesUpload = new Dropzone();$filesUpload->name = $imageName;$filesUpload->file_path = 'images/' . $imageName;$filesUpload->save();return view('form')->with('success', 'Files uplaoded successfully');}/*** Remove the specified resource from storage.** @param \App\Dropzone $dropzone* @return \Illuminate\Http\Response*/public function destroyFile($id){$dropzone = Dropzone::find($id);$dropzone->delete();return redirect()->back();}/*** Remove all resources from storage.** @param \App\Dropzone $dropzone* @return \Illuminate\Http\Response*/public function destroyAll(){$del_all = Dropzone::truncate();return view('form');}}The
viewAll()
function fetches all the item from your database and return an array or collection of arrays.
Thestore()
function stores the items in the database.
ThedestroyFile()
functions delete a particular item with reference to the item’s id.
ThedestroyAll()
function empty’s the table in the database.Step 6
Now all you need to do is to go to the form page on your browser, drag multiple files or images and drop on the form.
Then you click on the link
files
and It will give you the view below.Finally, go ahead and click on the ‘Delete’ button inside the image card to delete that particular file, then the ‘Delete All’ and you have your table empty.
Yea, I know you got value from this simple tutorial so drop your feedback on the comment box, that includes any challenge you may encounter in the process of application.
- AuthorPosts
- You must be logged in to reply to this topic.