PHPackages                             nadlambino/uploadable - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [File &amp; Storage](/categories/file-storage)
4. /
5. nadlambino/uploadable

ActiveLibrary[File &amp; Storage](/categories/file-storage)

nadlambino/uploadable
=====================

Automatically handle the file uploads for your models.

v1.2.0(1y ago)23431MITPHPPHP ^8.2

Since Jul 5Pushed 1y ago2 watchersCompare

[ Source](https://github.com/nadlambino/laravel-uploadable)[ Packagist](https://packagist.org/packages/nadlambino/uploadable)[ Docs](https://github.com/nadlambino/uploadable)[ GitHub Sponsors](https://github.com/NadLambino)[ RSS](/packages/nadlambino-uploadable/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (5)Dependencies (12)Versions (7)Used By (0)

Automatically handle the file uploads for your models.
======================================================

[](#automatically-handle-the-file-uploads-for-your-models)

[![Latest Version on Packagist](https://camo.githubusercontent.com/7fa3c05377ee78efb5547e3fb036d90967d20547b3e3c1c803d55c4ff01ebf56/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6e61646c616d62696e6f2f75706c6f616461626c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/nadlambino/uploadable)[![GitHub Tests Action Status](https://camo.githubusercontent.com/f985b9db560b7171071039f0ae693f576ac5b6eae39b7046ea154b019bdd7bb7/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6e61646c616d62696e6f2f75706c6f616461626c652f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/nadlambino/uploadable/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/e3743dccaf95ad426c57e4caaa2e57b6d77f7d53b481a42042be7c530563072c/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6e61646c616d62696e6f2f75706c6f616461626c652f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/nadlambino/uploadable/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/1aeea01de030a783778317565823b5d920dcaefcfb3f87d28382d4e712035f86/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6e61646c616d62696e6f2f75706c6f616461626c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/nadlambino/uploadable)

Table of Contents
-----------------

[](#table-of-contents)

- [Installation](#installation)
- [Usage](#usage)
- [Customization](#customization)
- [Manually Processing of File Uploads](#manually-processing-of-file-uploads)
- [Temporarily Disable the File Uploads](#temporarily-disable-the-file-uploads)
- [Uploading Files on Model Update](#uploading-files-on-model-update)
- [Uploading Files that are NOT from the Request](#uploading-files-that-are-not-from-the-request)
- [Relation Methods](#relation-methods)
- [Lifecycle and Events](#lifecycle-and-events)
- [Queueing](#queueing)
- [Testing](#testing)
- [Changelog](#changelog)
- [Contributing](#contributing)
- [Security Vulnerabilities](#security-vulnerabilities)
- [Credits](#credits)
- [License](#license)

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require nadlambino/uploadable
```

Publish and run the migrations with:

```
php artisan vendor:publish --tag="uploadable-migrations"
php artisan migrate
```

Important

You can add more fields to the uploads table according to your needs, but the existing fields should remain.

You can publish the config file with:

```
php artisan vendor:publish --tag="uploadable-config"
```

This is the contents of the published config file:

 uploadable.php```
return [

    /*
    |--------------------------------------------------------------------------
    | Validation
    |--------------------------------------------------------------------------
    |
    | Enable or disable the package's validation rules. Set to false if validation
    | has been performed separately, such as in a form request.
    |
    */
    'validate' => true,

    /*
    |--------------------------------------------------------------------------
    | Uploads Model
    |--------------------------------------------------------------------------
    |
    | Specify the model to use for uploads.
    |
    */
    'uploads_model' => \NadLambino\Uploadable\Models\Upload::class,

    /*
    |--------------------------------------------------------------------------
    | Delete Model on Upload Failure
    |--------------------------------------------------------------------------
    |
    | Automatically delete the newly created model if the upload process fails.
    | Applicable only to models that are being created.
    |
    */
    'delete_model_on_upload_fail' => true,

    /*
    |--------------------------------------------------------------------------
    | Rollback Model on Upload Failure
    |--------------------------------------------------------------------------
    |
    | Revert changes made to an existing model if the upload fails, restoring
    | the model's original attributes. Applies only to updated models.
    |
    */
    'rollback_model_on_upload_fail' => true,

    /*
    |--------------------------------------------------------------------------
    | Force Delete Uploads
    |--------------------------------------------------------------------------
    |
    | Determines whether uploaded files are permanently deleted. By default,
    | files are soft deleted, allowing for recovery.
    |
    */
    'force_delete_uploads' => false,

    /*
    |--------------------------------------------------------------------------
    | Replace Previous Uploads
    |--------------------------------------------------------------------------
    |
    | Determines whether uploaded files should be replaced with new ones. If
    | false, new files will be uploaded. If true, previous files will be
    | deleted once the new ones are uploaded.
    |
    */
    'replace_previous_uploads' => false,

    /*
    |--------------------------------------------------------------------------
    | Upload Queue
    |--------------------------------------------------------------------------
    |
    | Specify the queue name for uploading files. If set to null, uploads are
    | processed immediately. Otherwise, files are queued and processed.
    |
    */
    'upload_on_queue' => null,

    /*
    |--------------------------------------------------------------------------
    | Delete Model on Queued Upload Failure
    |--------------------------------------------------------------------------
    |
    | Delete the newly created model if a queued upload fails. Only affects models
    | that are being created.
    |
    */
    'delete_model_on_queue_upload_fail' => false,

    /*
    |--------------------------------------------------------------------------
    | Rollback Model on Queued Upload Failure
    |--------------------------------------------------------------------------
    |
    | Revert changes to a model if a queued upload fails, using the model's original
    | attributes before the upload started. Affects only updated models.
    |
    */
    'rollback_model_on_queue_upload_fail' => false,

    /*
    |--------------------------------------------------------------------------
    | Temporary Storage Disk
    |--------------------------------------------------------------------------
    |
    | Define the disk for temporary file storage during queued uploads. This
    | is where files are stored before being processed.
    |
    */
    'temporary_disk' => 'local',

    /*
    |--------------------------------------------------------------------------
    | Temporary URL
    |--------------------------------------------------------------------------
    |
    | Temporary URL for files that are uploaded locally is not supported by the
    | local disk. This setting allows you to specify the path and middleware to
    | access the files temporarily which uses a signed URL under the hood.
    | `expiration` can be a string or an instance of `DateTimeInterface`.
    |
    */
    'temporary_url' => [
        'path' => '/temporary',
        'middleware' => ['signed'],
        'expiration' => '1 hour',
    ],

    /*
    |--------------------------------------------------------------------------
    | Allowed Mimes by Extension
    |--------------------------------------------------------------------------
    |
    | Specify the mime types by extension that is allowed for uploads. Supports
    | categorization for images, videos, and documents with specific file
    | extensions.
    |
    */
    'mimes' => [
        'image' => ['jpeg', 'jpg', 'png', 'gif', 'bmp', 'svg', 'webp', 'ico'],
        'video' => ['mp4', 'webm', 'avi', 'mov', 'wmv', 'flv', '3gp', 'mkv', 'mpg', 'mpeg'],
        'document' => ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'csv', 'txt'],
    ],
];
```

---

Usage
-----

[](#usage)

Simply use the `NadLambino\Uploadable\Concerns\Uploadable` trait to your model that needs file uploads.

```
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use NadLambino\Uploadable\Concerns\Uploadable;

class Post extends Model
{
    use Uploadable;
}
```

Now, everytime you create or update a post, it will automatically upload the files that are included in your request and it will save the details in `uploads` table.

---

Customization
-------------

[](#customization)

### 1. Rules and Messages

[](#1-rules-and-messages)

Files from the request should have the following request names:

Request nameUse CaseRulesdocumentSingle document uploadsometimes, file, mimedocumentsMultiple document uploadssometimes, file, mimeimageSingle image uploadsometimes, image, mimeimagesMultiple image uploadssometimes, image, mimevideoSingle video uploadsometimes, mimevideosMultiple video uploadssometimes, mimeYou can add more fields or override the default ones by defining the protected `uploadRules`method in your model.

```
protected function uploadRules(): array
{
    return [
        // Override the rules for `document` field
        'document' => ['required', 'file', 'mime:application/pdf'],

        // Add a new field with it's own set of rules
        'avatar' => ['required', 'image', 'mime:png']
    ];
}
```

To add or override the rules messages, you can define the protected `uploadRuleMessages` method in your model.

```
public function uploadRuleMessages(): array
{
    return [
        'document.required' => 'The file is required.',
        'document.mime' => 'The file must be a PDF file.',
        'avatar.required' => 'The avatar is required.',
        'avatar.mime' => 'The avatar must be a PNG file.'
    ];
}
```

### 2. File Name and Upload Path

[](#2-file-name-and-upload-path)

You can customize the file name and path by defining the public methods `getUploadFilename` and `getUploadPath` in your model.

```
public function getUploadFilename(UploadedFile $file): string
{
    return str_replace('.', '', microtime(true)).'-'.$file->hashName();
}

public function getUploadPath(UploadedFile $file): string
{
    return $this->getTable().DIRECTORY_SEPARATOR.$this->{$this->getKeyName()};
}
```

Important

Make sure that the file name is completely unique to avoid overriding existing files.

### 3. Storage Options

[](#3-storage-options)

When you're uploading your files on cloud storage, oftentimes you want to provide options like visibility, cache control, and other metadata. To do so, you can define the `getUploadStorageOptions` in your model.

```
public function getUploadStorageOptions(): array
{
    return [
        'visibility' => 'public',
        'CacheControl' => 'max-age=315360000, no-transform, public'
    ];
}
```

### 4. Upload Disk

[](#4-upload-disk)

When you're uploading your files, sometimes you just upload it on your local disk. However for larger files, you may want to use `s3`. This can be with static method `uploadDisk`.

```
// Let us say that on your config/filesystems.php, your default disk is set to `local`.
// This method will create a user and will upload the file from the request, e.g., user avatar.
public function store(Request $request)
{
    User::create(...);
}

// While this method store the message and will upload the file from the request to `s3`.
public function store(Request $request)
{
    Message::uploadDisk('s3');
    Message::create(...);
}
```

### 5. Grouping of Uploads

[](#5-grouping-of-uploads)

When uploading a files for your model, sometimes you can have multiple file uploads for different purposes. For example, a post could have a file upload for thumbnail, banners, and gallery. This can be achieve with `uploadToCollection` method.

```
public function store(Request $request)
{
    Post::uploadToCollection('banner');

    Post::create(...);
}
```

Also, to retrieve file uploads of specific collection, you can use the scope query `fromCollection`.

```
$post = Post::query()
    ->with('image', fn ($query) => $query->fromCollection('banner'))
    ->find(...);
```

---

Manually Processing of File Uploads
-----------------------------------

[](#manually-processing-of-file-uploads)

File upload happens when the model's `created` or `updated` event was fired. If you're creating or updating a model quietly, you can call the `createUploads` or `updateUploads` method to manually process the file uploads.

```
public function update(Request $request, Post $post)
{
    $post->update($request->all());

    // If the post did not change, the `updated` event won't be fired.
    // So, we need to manually call the `updateUploads` method.
    if (! $post->wasChanged()) {
        $post->updateUploads();
    }
}
```

Important

Depending on your configuration, the `createUploads` will delete the model when the upload process fails, while `updateUploads` will update it to its original attributes.

Temporarily Disable the File Uploads
------------------------------------

[](#temporarily-disable-the-file-uploads)

You can temporarily disable the file uploads by calling the static method `disableUpload`.

```
public function update(Request $request, Post $post)
{
    // Temporarily disable the file uploads
    Post::disableUpload();

    $post->update($request->all());

    // Do more stuff here...

    // Manually process the uploads after everything you want to do
    $post->updateUploads();
}
```

### Caveat

[](#caveat)

When you are trying to create or update multiple models, the default behavior is that all of the files from the request will be uploaded and will be attached to all of these models. This is because these models are firing the `created` or `updated` event which triggers the upload process.

There are multiple ways to prevent this from happening such as:

- Silently create or update the models. By doing so, the `created` or `updated` event won't be fired which will not trigger the upload process. This may not be what you want if you have a model observer for these two events.
- Disable the upload process on the specific model by calling the `disableUpload()` method.
- Disable the upload process from the `NadLambino\Uploadable\Actions\Upload` action itself. The `Upload::disableFor()` method can accept a model class name, a model instance, or an array of each or both. See below example:

```
use NadLambino\Uploadable\Actions\Upload;

public function store(Request $request)
{
    // Disable the uploads for all of the instances of Post model
    Upload::disableFor(Post::class);

    // Files will be uploaded for User model
    User::create(...);

    // Files won't be uploaded for Post model
    Post::create(...);
}

// OR

public function update(Request $request, User $user)
{
     // Disable the uploads only for this specific $user
    Upload::disableFor($user);

    // Files won't be uploaded for this specific $user
    $user->update($request->validated());

    $anotherUser = User::find(...);

    // Files will be uploaded for this $anotherUser
    $anotherUser->update(...);
}
```

- Lastly, specifically instruct the `NadLambino\Uploadable\Actions\Upload` to process the upload only for the specific given model by calling the `Upload::onlyFor` method. This method has the same parameter signature as `Upload::disableFor` and ensure that only these given model classes or instances will be process.

```
use NadLambino\Uploadable\Actions\Upload;

public function store()
{
    // Process the uploads only for all of the instances of User model
    Upload::onlyFor(User::class);

    // Files will be uploaded for this User model
    User::create(...);

    // Files won't be uploaded for this Post model
    Post::create(...);
}

public function update(User $user)
{
    // Process the uploads only for this specific $user
    Upload::onlyFor($user);

    // Files will be uploaded for this specific $user
    $user->update(...);

    $anotherUser = User::find(...);

    // Files won't be uploaded for this $anotherUser
    $anotherUser->update(...)
}
```

Also, there is `NadLambino\Uploadable\Actions\Upload::enableFor()` method if you need to delist a model from the disabled list. It is different from `onlyFor` in a way that `onlyFor` method ensures that the files were only be uploaded to the given models while `enableFor` just simply removes the given models from the disabled list.

All of these methods could also work even when you are uploading on a queue.

Note

When calling the `disableFor` method, it will remove the given model from the list of `onlyFor` models. Same goes when calling the `onlyFor` method, it will remove the given model from the list of disabled models.

---

Uploading files on model update
-------------------------------

[](#uploading-files-on-model-update)

By default, when you update a model, the files from the request will add up to the existing uploaded files. If you want to replace the existing files with the new ones, you can configure it in the `uploadable.php` config file.

```
'replace_previous_uploads' => true,
```

Or alternatively, you can call the static method `replacePreviousUploads` before updating the model.

```
public function update(Request $request, Post $post)
{
    // Replace the previous uploads
    Post::replacePreviousUploads();

    $post->update($request->all());
}
```

Note

The process of deleting the previous uploads will only happen when new files were successfully uploaded.

---

Uploading files that are NOT from the request
---------------------------------------------

[](#uploading-files-that-are-not-from-the-request)

If you wish to upload a file that is NOT directly from the request, you can do so by calling the `uploadFrom` method. This method can accept an instance or an array of `Illuminate\Http\UploadedFile` or a string path of a file that is uploaded on your `temporary_disk`.

```
// DO
$post->uploadFrom($request->file('image'));

// OR
$post->uploadFrom(new UploadedFile(...));

// OR
$post->uploadFrom([
    $request->file('image'),
    $request->file('avatar')
]);

// OR
$fullpath = ... // The path of the file that is uploaded in your `temporary_disk`. This could be something like an image that was modified by `ImageIntervention` then temporarily stored before uploading

$post->uploadFrom($fullpath);

// OR
$post->uploadFrom([
    $fullpath1,
    $fullpath2
]);

// OR even a mixed of both
$post->uploadFrom([
    $request->file('image'),
    $fullpath,
]);

$post->save();
```

Important

Make sure that you've already validated the files that you're passing here as it does not run any validation like it does when uploading directly from the request.

---

Relation methods
----------------

[](#relation-methods)

There are already pre-defined relation method for specific upload type.

```
// Relation for all types of uploads
public function upload(): MorphOne { }

// Relation for all types of uploads
public function uploads(): MorphMany { }

// Relation for uploads where extension or type is in the accepted image mimes
public function image(): MorphOne { }

// Relation for uploads where extension or type is in the accepted image mimes
public function images(): MorphMany { }

// Relation for uploads where extension or type is in the accepted video mimes
public function video(): MorphOne { }

// Relation for uploads where extension or type is in the accepted video mimes
public function videos(): MorphMany { }

// Relation for uploads where extension or type is in the accepted document mimes
public function document(): MorphOne { }

// Relation for uploads where extension or type is in the accepted document mimes
public function documents(): MorphMany { }
```

Important

MorphOne relation method sets a limit of one in the query.

---

Lifecycle and Events
--------------------

[](#lifecycle-and-events)

During the entire process of uploading your files, events are being fired in each step. This comes very helpful if you need to do something in between these steps or just for debugging purposes.

EventWhen It Is FiredWhat The Event Receives When Dispatched`NadLambino\Uploadable\Events\BeforeUpload::class`Fired before the upload process starts`Model $uploadable`, `array $files`, `UploadOptions $options``NadLambino\Uploadable\Events\StartUpload::class`Fired when the upload process has started and its about to upload the first file in the list. This event may fired up multiple times depending on the number of files that is being uploaded`Model $uploadable`, `string $filename`, `string $path``NadLambino\Uploadable\Events\AfterUpload::class`Fired when the file was successfully uploaded and file information has been stored in the `uploads` table. This event may fired up multiple times depending on the number of files that is being uploaded`Model $uploadable`, `Upload $upload``NadLambino\Uploadable\Events\CompleteUpload::class`Fired when all of the files are uploaded and all of the necessary clean ups has been made`Model $uploadable`, `Collection $uploads``NadLambino\Uploadable\Events\FailedUpload::class`Fired when an exception was thrown while trying to upload a specific file.`Throwable $exception`, `Model $uploadable`If you want to do something before the file information is stored to the `uploads` table, you can define the `beforeSavingUpload` public method in your model. This method will be called after the file is uploaded in the storage and before the file information is saved in the database.

```
public function beforeSavingUpload(Upload $upload, Model $model) : void
{
    $upload->additional_field = "some value";
}
```

Alternatively, you can statically call the `beforeSavingUploadUsing` method and pass a closure. The closure will receive the same parameters as the `beforeSavingUpload` method. Just make sure that you call this method before creating or updating the model. Also, `beforeSavingUploadUsing` has the higher precedence than the `beforeSavingUpload` allowing you to override it when needed.

```
Post::beforeSavingUploadUsing(function (Upload $upload, Post $model) use ($value) {
    $model->additional_field = $value;
});

$post->save();
```

Important

Remember, when you're on a queue, you are actually running your upload process in a different application instance so you don't have access to the current application state like the request object. Also, make sure that the closure and its dependencies you passed to the `beforeSavingUploadUsing` method are serializable.

---

Queueing
--------

[](#queueing)

You can queue the file upload process by defining the queue name in the config.

```
'upload_on_queue' => null,
```

Alternatively, you can also call the static method `uploadOnQueue`.

```
Post::uploadOnQueue('default');

$post->save();
```

---

Testing
-------

[](#testing)

```
composer test
```

---

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

---

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

---

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

---

Credits
-------

[](#credits)

- [Ronald Lambino](https://github.com/nadlambino)
- [All Contributors](../../contributors)

---

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance39

Infrequent updates — may be unmaintained

Popularity17

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity57

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~4 days

Total

5

Last Release

661d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/c2b2938add7fe0c000deb7f15e9259c27039409e918783b4a7cf2b9b4e3f35d0?d=identicon)[nadlambino](/maintainers/nadlambino)

---

Top Contributors

[![nadlambino](https://avatars.githubusercontent.com/u/50892397?v=4)](https://github.com/nadlambino "nadlambino (127 commits)")

---

Tags

file-uploadslaravelphplaraveluploadableNadLambino

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/nadlambino-uploadable/health.svg)

```
[![Health](https://phpackages.com/badges/nadlambino-uploadable/health.svg)](https://phpackages.com/packages/nadlambino-uploadable)
```

###  Alternatives

[spatie/livewire-filepond

Upload files using Filepond in Livewire components

306452.7k3](/packages/spatie-livewire-filepond)[elegantly/laravel-invoices

Store invoices safely in your Laravel application

23131.8k](/packages/elegantly-laravel-invoices)[vormkracht10/laravel-mails

Laravel Mails can collect everything you might want to track about the mails that has been sent by your Laravel app.

24149.7k](/packages/vormkracht10-laravel-mails)[mwguerra/filemanager

A full-featured file manager package for Laravel and Filament v5 with dual operating modes, drag-and-drop uploads, S3/MinIO support, and comprehensive security features.

718.5k1](/packages/mwguerra-filemanager)[codebar-ag/laravel-flysystem-cloudinary

Cloudinary Flysystem v1 integration with Laravel

1224.9k2](/packages/codebar-ag-laravel-flysystem-cloudinary)[kalynasolutions/laravel-tus

Laravel package for handling resumable file uploads with tus protocol and native Uppy.js support without additional tus servers

5261.8k1](/packages/kalynasolutions-laravel-tus)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
