Dead simple Laravel backend support for FilePond js.

Overview

Laravel FilePond Backend

Latest Version on Packagist Total Downloads

This package provides a straight forward backend support for Laravel application to work with FilePond file upload javascript library. Supports both single and multiple file uploads. This package keeps tracks of all the uploaded files and provides an easier interface for the user to interact with the files. It also comes with an artisan command to clean up temporary files after they have expired.

Installation

Install the package via composer:

composer require rahulhaque/laravel-filepond

Laravel

Publish the configuration and migration files.

php artisan vendor:publish --provider="RahulHaque\Filepond\FilepondServiceProvider"

Run the migration.

php artisan migrate

Quickstart

Before we begin, first install and integrate the FilePond library in your project any way you prefer.

We will make up a scenario for the new-comers to get them started with FilePond right away.

Let's assume we are updating user avatar like the form below.

<form action="{{ route('avatar') }}" method="post">
    @csrf
    
    <intput type="file" name="avatar" required/>

    <button type="submit">Submit</button>
</form>

<script>
    // Set default FilePond options
    FilePond.setOptions({
        server: {
            process: "{{ config('filepond.server.process') }}",
            revert: "{{ config('filepond.server.revert') }}",
            headers: {
                'X-CSRF-TOKEN': "{{ @csrf_token() }}",
            }
        }
    });

    // Create the FilePond instance
    FilePond.create(document.querySelector('input[type="file"]'));
</script>

Now selecting a file with FilePond input field will upload the file in the temporary directory immediately and append the hidden input in the form. Submit the form to process the uploaded file like below in your controller.

In UserAvatarController.php get and process the submitted file by calling the moveTo() method from the Filepond facade which will return the moved file information as well as delete the file from the temporary storage.

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Storage;
use RahulHaque\Filepond\Facades\Filepond;

class UserAvatarController extends Controller
{
    /**
     * Update the avatar for the user.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        $this->validate($request, ['avatar' => 'required']);
    
        $filename = 'avatar-' . auth()->id();
    
        $fileInfo = Filepond::field($request->avatar)
            ->moveTo(Storage::disk('avatar')->path($filename));
            
        // dd($fileInfo);
        // [
        //     "id" => 1,
        //     "dirname" => "/filepath/storage/app/public/avatars",
        //     "basename" => "avatar-1.png",
        //     "extension" => "png",
        //     "filename" => "avatar-1",
        // ];
    
        auth()->user()->update([
            'avatar' => $fileInfo['basename']
        ]);
    }
}

This is the quickest way to get started. This package has already implemented all the classes and controllers for you. Next we will discuss about all the nitty gritty stuffs available.

Usage

Configuration

First have a look at the ./config/filepond.php to know about all the options available out of the box.

Temporary Storage

This package adds a disk to Laravel's filesystem config named filepond which points towards ./storage/app/filepond directory for temporary file storage. Set your own if needed.

Command

This package includes a php artisan filepond:clear command to clean up the expired files from the temporary storage. File expiration minute can be set in the config file, default is 30 minutes. Add this command to your scheduled command list to run daily. Know more about task scheduling here - Scheduling Artisan Commands

This command takes --all option which will truncate the Filepond model and delete everything inside the temporary storage regardless they are expired or not. This is useful when you lost track of your uploaded files and want to start clean.

Methods

field()

Filepond::field($field) is a required method which tell the library which FilePond form field to work with. Chain the rest of the methods as required.

getFile()

Filepond::field()->getFile() method returns the file object same as the Laravel's $request->file() object. For multiple uploads, it will return an array of uploaded file objects. You can then process the file manually any way you want.

Note: Processing the file object manually will not update the associated Filepond model which is used to keep track of the uploaded files. However the expired files will be cleaned up as usual by the scheduled command. It is recommended that you either call the delete() method or update the underlying model by calling getModel() method after the processing is done.

getModel()

Filepond::field()->getModel() method returns the underlying Laravel Filepond model for the given field. This is useful when you have added some custom fields to update in the published migration file for your need.

copyTo()

Calling the Filepond::field()->copyTo($pathWithFilename) method will copy the file from the temporary storage to the path provided along with the filename and will set the file extension automatically. This method will return the copied file info along with filepond model id. For multiple file upload, it will return an array of copied files info. Also note that multiple files will be copied with trailing incremental values like $filename-{$i}.

moveTo()

Calling the Filepond::field()->moveTo($pathWithFilename) method works the same way as copy method. One thing it does extra for you is delete the file after copying, respecting the value of soft_delete configuration for Filepond model.

delete()

Calling the Filepond::field()->delete() method will delete the temporary file respecting the soft delete configuration for Filepond model. This method is useful when you're manually handling the file processing using getFile() method.

Traits

There is a HasFilepond trait available to get the temporary files uploaded by the users.

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use RahulHaque\Filepond\Traits\HasFilepond;

class User extends Authenticatable
{
    use HasFilepond;
}

Now you can get all the file info uploaded by a single user like this.

User::find(1)->fileponds;

Testing

composer test

Changelog

Please see CHANGELOG for more information what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

Comments
  •  The payload is invalid

    The payload is invalid

    I did a basic configuration of filepond. Client side:

    FilePond.setOptions({
            credits: false,
            allowMultiple: true,
            server: {
                url: 'url',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                }
            }
        });
    
    FilePond.create(document.querySelector('input[name="nuovo_file"]'));
    

    Server side: $fileInfo = Filepond::field('nuovo_file')->getFile();

    I have this error: The payload is invalid. {"userId":1,"exception":"[object] (Illuminate\Contracts\Encryption\DecryptException(code: 0): The payload is invalid. at /vendor/laravel/framework/src/Illuminate/Encryption/Encrypter.php:214

    if I use this code on server side work fine:

    $file=$request->file('nuovo_file');
    $nomeFile=$file->getClientOriginalName();
    ........
    
    

    Can some one help me?

    opened by nemo3000 16
  • Unable to manually delete temporary files.

    Unable to manually delete temporary files.

    I had a job to create a "post", after the post is created all the temporary files should be deleted. But weird things happened, pls look at the codes.

    public function handle(): void
        {
            $showcase = new Showcase([
                "uuid" => $this->uuid->toString(),
                "title" => $this->title,
                "description" => $this->description,
                "slug" => Str::slug($this->title),
            ]);
    
            $showcase->authoredBy($this->author);
            $showcase->save();
    
            $showcase_cover_image = Filepond::field($this->showcase_cover_image); // single upload
            $showcase_images = Filepond::field($this->showcase_images); // chunk upload 
            
            $showcase_cover_image->delete(); // this is not deleted 
            $showcase_images->delete(); // this is deleted
        }
    
    opened by jameswong3388 8
  • Size not available

    Size not available

    When I want to use FilePoster I get size unavailable. Is there something I missed with my codes as below?

    ` FilePond.registerPlugin( FilePondPluginFilePoster, FilePondPluginImagePreview );

    FilePond.create(document.querySelector('input[name="cover"]'));
    FilePond.setOptions({
        server: {
            url: "{{ config('filepond.server.url') }}",
            headers: {
                'X-CSRF-TOKEN': "{{ @csrf_token() }}",
            },
        },
        files: [
            {
                source: "http://127.0.0.1:8000/storage/covers/project-cover-639cf605b3251.png",
                options: {
                    type: 'local',
                    metadata: {
                        poster: "http://127.0.0.1:8000/storage/covers/project-cover-639cf605b3251.png",
                    },
                }
            }
        ]
    });
    

    `

    I am getting error Argument 1 passed to RahulHaque\Filepond\Services\FilepondService::offset() must be of the type string

    How should I go about this? Thanks

    opened by kurtomerfaruk 7
  • Attempt to read property

    Attempt to read property "disk" on null"

    Dear Sir When I'm trying to move and validate or any other methods after field() it throws null errors.

    Filepond::field($request->input('logo_url'))->validate(['logo_url' => 'required|image|max:3000']);
            $fileName = \Str::random(20) . '_brand';
            $destination = 'uploads/brand/';
    $fileInfo = Filepond::field($request->input('logo_url'))
            ->moveTo($destination . $fileName);
    

    Any help will be appreciated.

    opened by aligulzar729 7
  • resize images before uploading

    resize images before uploading

    Hello , have a nice day, first of all thank you so much for this amazing package , it helps me a lot. second thing I am wondering if is there any a proper way that I can use to resize images before uploading them by using this package.

    Thanks in advance.

    opened by allaghi 6
  • fix DB connection issue on composer install

    fix DB connection issue on composer install

    There was an issue with the database connection while installing the package.

    Screen Shot 2021-09-16 at 10 32 08 PM

    In this workflow configuration, it also throws a DB exception

    Screen Shot 2021-09-16 at 9 08 44 PM

    I've set up a test repo with the github workflows installed. Please check the outcome of workflowsform here. .

    opened by nishalgurung4 5
  • Error in laravel 8 jetstream

    Error in laravel 8 jetstream

    I got this error

    Illuminate\Contracts\Encryption\DecryptException: The payload is invalid. in file D:\Software Projects\atc\vendor\laravel\framework\src\Illuminate\Encryption\Encrypter.php on line 223
    
    #0 D:\Software Projects\atc\vendor\laravel\framework\src\Illuminate\Encryption\Encrypter.php(158): Illuminate\Encryption\Encrypter->getJsonPayload()
    #1 D:\Software Projects\atc\vendor\laravel\framework\src\Illuminate\Support\Facades\Facade.php(261): Illuminate\Encryption\Encrypter->decrypt()
    #2 D:\Software Projects\atc\vendor\rahulhaque\laravel-filepond\src\AbstractFilepond.php(153): Illuminate\Support\Facades\Facade::__callStatic()
    #3 D:\Software Projects\atc\vendor\rahulhaque\laravel-filepond\src\AbstractFilepond.php(58): RahulHaque\Filepond\AbstractFilepond->decrypt()
    #4 D:\Software Projects\atc\vendor\rahulhaque\laravel-filepond\src\Filepond.php(19): RahulHaque\Filepond\AbstractFilepond->setFieldValue()
    #5 D:\Software Projects\atc\vendor\laravel\framework\src\Illuminate\Support\Facades\Facade.php(261): RahulHaque\Filepond\Filepond->field()
    

    here is the snippet

    Filepond::field($request->document)
                ->validate(['document' => 'required|file|image']);
    
    opened by eskiesirius 4
  • Multiple Uploads Saved as Single Item

    Multiple Uploads Saved as Single Item

    Hello,

    Thank you for your work on this package, it is exactly what I need to make the connection between Filepond, Inertia and Laravel.

    I'm attempting to upload multiple images and it looks that is successful at least for the temporary files. However, when I go to the storage path, I only see one image, instead of 'x' amount of images. I'm not sure if I'm missing a step or the functionality is actually broken.

    Filepond Instance:

    <file-pond
                                    name="image[]"
                                    ref="pond"
                                    credits=""
                                    allowMultiple="true"
                                    maxFiles="5"
                                    label-idle="Click to choose image, or drag here..."
                                    accepted-file-types="image/jpg, image/jpeg, image/png"
                                    max-file-size="3MB"
                                    @processfile="handleFilePondProcess"
                                    @removefile="handleFilePondRemoveFile"
                                />
    

    Vue data array:

    data() {
            return {
                products: this.products,
                stores: this.stores,
                brands: this.brands,
                form: this.$inertia.form({
                    _method: "post",
                    product: "",
                    brand: "",
                    store: "",
                    tags: "",
                    image: [],
                    title: "",
                    link: "",
                    discount: "",
                    price: "",
                    price_extras: "",
                    description: ""
                })
            };
        },
    

    Vue methods:

     handleFilePondProcess: function(error, file) {
                // Set the server id from response
                this.form.image = file.serverId;
            },
            handleFilePondRemoveFile: function(error, file) {
                // Remove the server id on file remove
                this.form.image = null;
            }
    

    Controller:

     Filepond::field($request->image)->moveTo('deals/deal-' . $deal->id);
    
    opened by JD456976 3
  • Laravel 9?

    Laravel 9?

    How soon will you enable Laravel 9 support?

    Problem 1
        - Root composer.json requires rahulhaque/laravel-filepond ^1.4 -> satisfiable by rahulhaque/laravel-filepond[v1.4.8].
        - rahulhaque/laravel-filepond v1.4.8 requires illuminate/support ^7.0|^8.0 -> found illuminate/support[v7.0.0, ..., 7.x-dev, v8.0.0, ..., 8.x-dev] but these were not loaded, likely because it conflicts with another require.
    
    opened by Inkwadra 3
  • How to access the data?

    How to access the data?

    Screenshot_116 I using a spatie media, so i need a string of the image path. for now i just do like on the screenshot, and i believe this is incorrect ways. thank for your response

    opened by xfkrahmad 2
  • getFile() function

    getFile() function

    I'm trying to use the getFile() function according to the documentation "$fileInfo = Filepond::field($request->file)->getFile()", but the response is an empty array. Need help

    opened by 1JP 2
Releases(v1.8.10)
  • v1.8.10(Jun 1, 2022)

  • v1.7.10(May 31, 2022)

  • v1.7.9(May 7, 2022)

  • v1.7.8(Apr 30, 2022)

  • v1.6.8(Feb 22, 2022)

  • v1.5.8(Feb 15, 2022)

  • v1.4.8(Dec 31, 2021)

    1.4.8 - 2021-12-31

    • Added support for chunk upload with resume capability. ✨
    • Added option to change visibility when using third party storage.
    • Updated quickstart example in readme.
    • Updated ./filepond/config.php to change url from one place.
    Source code(tar.gz)
    Source code(zip)
  • v1.3.8(Dec 25, 2021)

  • v1.3.7(Dec 23, 2021)

    1.3.7 - 2021-12-24

    • Added support for third party storage. ✨
    • File submit response now contains file location and URL for better management.
    • Code base restructure and performance improvement.
    Source code(tar.gz)
    Source code(zip)
  • v1.2.7(Oct 31, 2021)

  • v1.2.6(Sep 17, 2021)

  • v1.2.5(Aug 5, 2021)

  • v1.2.4(Jul 24, 2021)

  • v1.2.3(Jul 21, 2021)

  • v1.2.2(Jul 21, 2021)

    1.2.2 - 2021-07-21

    • Added controller level validation to validate files before moving from temporary storage. ✨
    • Addressed workaround where FilePond won't work when laravel debugbar is installed.
    • Moved to service implementation for cleaner controller code.
    • Fixed an issue where vendor:publish will create duplicate migrations.
    • Added test cases for filepond revert route.
    • Added test cases for filepond:clear command.
    • Updated documentation for related changes.
    Source code(tar.gz)
    Source code(zip)
  • v1.1.2(Jul 16, 2021)

  • v1.0.2(May 22, 2021)

    1.0.2 - 2021-05-22

    • Validation message will now include field name.
    • Test cases added for filepond process route.
    • Reduced package bundle size.
    Source code(tar.gz)
    Source code(zip)
  • v1.0.1(May 21, 2021)

    1.0.1 - 2021-05-21

    • Multiple file uploads will be returned as array of objects as per Laravel standard.
    • An issue with temporary storage not being cleared fixed.
    • Test cases added for Filepond model.
    Source code(tar.gz)
    Source code(zip)
  • v1.0.0(May 20, 2021)

    1.0.0 - 2021-05-20

    • Supports FilePond process and revert routes.
    • Built-in artisan command to clean up temporary storage.
    • Trait support for tracking user uploads.
    Source code(tar.gz)
    Source code(zip)
  • v0.5.3(Jun 1, 2022)

    0.5.3 - 2022-06-02

    • Rule::filepond($rules) Laravel 7 specific validation issue fixed.
    • validate() method deprication notice added.
    • Multiple file uploads sometime won't move to location fixed.
    Source code(tar.gz)
    Source code(zip)
  • v0.4.2(May 7, 2022)

  • v0.4.1(May 5, 2022)

    0.4.1 - 2022-05-05

    • Added custom Rule::filepond() to validate uploaded files. ✨
    • Added option to getDataURL() from file. Know more about the format here.
    • Readme updated with new validation example.
    Source code(tar.gz)
    Source code(zip)
  • v0.3.1(Jan 2, 2022)

    0.3.1 - 2021-12-31

    • Added support for chunk upload with resume capability. ✨
    • Added option to change visibility when using third party storage.
    • Updated quickstart example in readme.
    • Updated ./filepond/config.php to change url from one place.
    Source code(tar.gz)
    Source code(zip)
  • v0.2.1(Dec 25, 2021)

  • v0.2.0(Dec 24, 2021)

    0.2.0 - 2021-12-25

    • Added support for third party storage. ✨
    • File submit response now contains file location and URL for better management.
    • Code base restructure and performance improvement.
    • Laravel 7 test cases added.
    Source code(tar.gz)
    Source code(zip)
  • v0.1.0(Nov 2, 2021)

Owner
rahulhaque
Learn. Think. Code. Solve. Repeat.
rahulhaque
Laravel application project as Sheina Online Store backend to be built with Laravel and VueJS

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Boas Aditya Christian 1 Jan 11, 2022
Laravel Backend API for the tutorial (Granular permissions with Laravel APIs & React frontend)

Laravel Granular Permissions Backend Getting Started Clone the repository. Install the dependencies composer install Update .env database credentials

Munaf Aqeel Mahdi 4 May 10, 2022
Awes.io // boilerplate based on Vue, Nuxt, TailwindCSS plus Laravel as a backend. 🤟

Platform for Interactive Business Applications 10x faster to create than the traditional way • 3x increase application experiences • 60% decrease in d

Awes.io 753 Dec 30, 2022
Laravel Backend for Learnbot app

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Mobile & Backend developer 4 May 18, 2021
Web application with Laravel in Backend and VueJS in Frontend

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Benjdia Saad 1 Oct 12, 2021
Backend application using Laravel 9.x REST APIs for games topup from digiflazz.com and payment gateway using xendit.co

TOPUP - Laravel 9.x REST API Documentation is still on progress. For now, you can fork this postman collection Installation Clone this project git clo

Muhammad Athhar Kautsar 46 Dec 17, 2022
Video Chat application built using Metered Video SDK, with PHP Laravel Backend and JavaScript Front-End

Group Video Chat App with PHP Laravel and JavaScript Powered by Metered Video SDK Overview This application is a highly scalable group video calling a

null 2 Aug 18, 2022
A web app for detecting backend technologies used in a web app, Based on wappalyzer node module

About Techdetector This a web fingerprinting application, it detects back end technologies of a given domain by using the node module wappalyzer. And

Shobi 17 Dec 30, 2022
Generator-hedley - Scaffold a headless Drupal backend, Angular app client, and Behat tests

generator-hedley Scaffold a headless Drupal backend, Angular app client, and Behat tests Hedley is a yeoman generator that scaffolds a headless Drupal

null 99 Jun 3, 2022
PcTools is a proyect developed using {JavaScript,HTML5,CSS} for frontend and {PHP => Mysql} for backend.

PcTools-Proyect PcTools is a proyect developed using {JavaScript,HTML5,CSS} for frontend and {PHP => Mysql} for backend. Future Improvements # Replace

Ihab Fallahy 1 Feb 5, 2022
The admin (Backend Dashboard) for Charcoal

Charcoal Admin Module The standard Charcoal Admin Control Panel (Backend Dashboard). How to install The preferred (and only supported) way of installi

Locomotive 11 Jul 5, 2022
View themes is a simple package to provide themed view support to Laravel.

Laravel View Themes View themes is a simple package to provide themed view support to Laravel. Installation Add alexwhitman/view-themes to the require

Alex Whitman 15 Nov 29, 2022
A simple drop-in solution for providing UUID support for the IDs of your Eloquent models.

Introduction A simple drop-in solution for providing UUID support for the IDs of your Eloquent models. Both v1 and v4 IDs are supported out of the box

GoldSpec Digital 501 Jan 4, 2023
Laravel Sanctum support for Laravel Lighthouse

Lighthouse Sanctum Add Laravel Sanctum support to Lighthouse Requirements Installation Usage Login Logout Register Email Verification Forgot Password

Daniël de Wit 43 Dec 21, 2022
A package that uses blade templates to control how markdown is converted to HTML inside Laravel, as well as providing support for markdown files to Laravel views.

Install Install via composer. $ composer require olliecodes/laravel-etched-blade Once installed you'll want to publish the config. $ php artisan vendo

Ollie Codes 19 Jul 5, 2021
Laravel package to generate and to validate a UUID according to the RFC 4122 standard. Only support for version 1, 3, 4 and 5 UUID are built-in.

Laravel Uuid Laravel package to generate and to validate a universally unique identifier (UUID) according to the RFC 4122 standard. Support for versio

Christoph Kempen 1.7k Dec 28, 2022
📦 Adds Laravel Packages Support to Lumen and Vendor Publish Artisan Command.

Laravel Package Support for Lumen: Makes Lumen compatible with Laravel Packages. You can use any Laravel Packages in Lumen by installing Larasupport Package.

Irfaq Syed 127 Dec 17, 2022
CORS (Cross-Origin Resource Sharing) support for Laravel and Lumen

Description This package adds Cross-Origin Resource Sharing (CORS) support to your Laravel application. The package is based on Framework agnostic (PS

null 48 Feb 1, 2020
Multi theme support for Laravel application

Multi theme support for Laravel application This Laravel package adds multi-theme support to your application. It also provides a simple authenticatio

QiroLab 287 Dec 29, 2022