# Laravel Has Files documentation (v8.x)

> Canonical: https://pharaonic.dev/packages/laravel/has-files/8.x  
> Version: v8.x (latest release 8.0.0, 2026-11-29)  
> Install: composer require pharaonic/laravel-has-files  
> Repository: https://github.com/Pharaonic/laravel-has-files  
> All versions: https://pharaonic.dev/packages/laravel/has-files/13.x.md https://pharaonic.dev/packages/laravel/has-files/12.x.md https://pharaonic.dev/packages/laravel/has-files/11.x.md https://pharaonic.dev/packages/laravel/has-files/10.x.md https://pharaonic.dev/packages/laravel/has-files/9.x.md https://pharaonic.dev/packages/laravel/has-files/8.x.md https://pharaonic.dev/packages/laravel/has-files/7.x.md https://pharaonic.dev/packages/laravel/has-files/6.x.md

:::badges
- Laravel Package {color=blue}
- v8.0.0 {color=green}
- MIT License {color=purple}
:::

# Laravel Has Files

Has Files attaches files to your Eloquent models. A model declares its fileables in one `fileables()` method, such as a single `cover` image, an ordered `gallery`, an `intro` video or a `media` list mixing images and PDFs. Reading `$product->file('gallery')` gives you a handler that lists, adds, orders, enables and removes files. Assigning files in `create()` or `update()` saves them with the model. Storage, URLs, thumbnails and processing come from [Laravel Uploader](https://pharaonic.dev/packages/laravel/uploader), so every file is an Uploader `Upload`.

:::features
### Typed Fileables
Declare images, videos, audio, documents, archives or a mixed list, each with only the settings that apply to it.

### Single or Ordered
One file by default, or an ordered list with append, insert, move and reorder.

### Saved With the Model
Files given to create, update or save are checked before the model is written, then stored with it.

### Checked by Content
File types are detected from the content, never from the name, with size, count and custom rules.

### Activation and Metadata
Enable or disable each file and keep captions or alt text with it, without touching the upload.

### Processing on Request
Thumbnails, resizing, conversion and FFmpeg video and audio processing, only when you ask for them.

### Shared Uploads
Attach one upload to several models; it is never deleted while a file still uses it.

### Safe Concurrency
Writes lock the owner row, so two requests never break the order or the file limit.
:::

:::info Quick Tip
Eager load `files` when you list models, and every fileable reads from it without another query.
:::

## Installation

Install the package with Composer. Laravel discovers the service provider, and the migrations run with your own.

### Requirements

- PHP 8.0 or 8.1
- Laravel 8.75 or newer within 8.x
- `pharaonic/laravel-uploader` 8.1.1 or newer within 8.x (installed automatically)
- The GD or Imagick extension, only for thumbnails and image processing
- FFmpeg and FFprobe, only for video and audio processing, with a queue worker unless processing is synchronous

### Composer Installation

```bash title="Terminal" no-line-numbers
composer require pharaonic/laravel-has-files
```

### Run Migrations

The package loads its migrations automatically. `migrate` creates the Uploader's `uploads` table and the `files` table:

```bash title="Terminal" no-line-numbers
php artisan migrate
```

Set the [`table`, `connection` and `key_type` options](#configuration) before you run it: the migration reads them. To copy the migrations into `database/migrations` instead, publish them:

```bash title="Terminal" no-line-numbers
php artisan vendor:publish --tag=files-migrations
```

### Publish Configuration

Publish the configuration file to `config/pharaonic/files.php` when you need to change a default:

```bash title="Terminal" no-line-numbers
php artisan vendor:publish --tag=files-config
```

The validation messages (English and Arabic) publish with `--tag=files-translations`. The `pharaonic` and `laravel-has-files` tags publish everything.

:::success Installation Complete
You're all set! Add the HasFiles concern to a model and declare its first fileable in [Basic Usage](#basic-usage).
:::

## Configuration

The options live under `pharaonic.files`, published to `config/pharaonic/files.php`:

```php title="config/pharaonic/files.php"
return [
    'model' => \Pharaonic\Laravel\Files\Models\File::class,
    'table' => 'files',
    'connection' => null,
    'key_type' => 'integer',
    'detach_on_soft_delete' => false,
    'keep_replaced_uploads' => false,
];
```

| Option | Default | Description |
| --- | --- | --- |
| `model` | `Models\File` | The attachment model. A custom model must extend `Pharaonic\Laravel\Files\Models\File` |
| `table` | `files` | The table of the attachment rows |
| `connection` | `null` | The database connection; `null` is the application's default |
| `key_type` | `integer` | The `fileable_id` column type: `integer`, `uuid`, `ulid` or `string`, matching your owners' keys |
| `detach_on_soft_delete` | `false` | Detach the files on a soft delete too. By default a soft delete keeps them, so `restore()` brings them back |
| `keep_replaced_uploads` | `false` | Keep the upload of a replaced file, unlinked from the model. By default it is deleted; a fileable overrides this with `keepReplacedUploads()` |

`table`, `connection` and `key_type` are read when the migration runs. Changing them afterwards needs a migration of your own.

### Connections

Every write locks the owner row and runs in one transaction with it, so the files table must be on the owners' connection. Set `connection` when your owners use a connection other than the default. A write on a model whose connection differs is refused before anything is stored.

:::warning One owner key type per table
`fileable_id` has one type for every owner. On PostgreSQL, a `string` column cannot be compared with integer keys, so mix owner key types only on MySQL, MariaDB or SQLite. In a multi-tenant application with one database per tenant, keep the files table in the tenant's database, so identical owner ids never meet.
:::

### Storage and processing defaults

Has Files stores every file through [Laravel Uploader](https://pharaonic.dev/packages/laravel/uploader), so the storage and processing defaults are the Uploader's. To change them, publish the Uploader's config:

```bash
php artisan vendor:publish --tag=uploader-config
```

It is published to `config/pharaonic/uploader.php`. The options Has Files relies on:

| Option | Default | Used when |
| --- | --- | --- |
| `disk` | `FILESYSTEM_DISK` | A fileable does not call `disk()` |
| `path` | `/` | Always: a fileable's `path()` is a directory under it |
| `visibility` | `private` | A fileable does not call `visibility()` (non-local disks) |
| `expire` | `30` | `url` of private files on S3, and `temporaryUrl()` without minutes |
| `thumbnail` | width `400` | `thumbnail()` is called without a size, and the width of video thumbnails |
| `max_pixels` | `50000000` | Always: larger images and video frames are refused |
| `ffmpeg` | `ffmpeg`, `ffprobe` | Video and audio processing |
| `processing` | queued | Video and audio processing: queue, tries, timeout, or `sync` |

A fileable's own settings win over these defaults for its files only:

```php
File::make('cover')
    ->images()
    ->disk('s3')               // instead of the Uploader's disk
    ->path('products/covers')  // under the Uploader's path
    ->visibility('public'),    // instead of the Uploader's visibility
```

Nothing is processed unless the fileable asks for it, so the thumbnail, FFmpeg and processing options apply only to fileables that call processing methods (see [Processing](#processing)). No fileable setting bypasses `max_pixels`.

Has Files' own config, `config/pharaonic/files.php`, holds only the options above: the model, table, connection and key type.

### A custom model

Extend the model to add your own methods, then point `model` at it:

```php title="app/Models/Attachment.php"
namespace App\Models;

use Pharaonic\Laravel\Files\Models\File;

class Attachment extends File
{
    public function caption(): ?string
    {
        return $this->meta->caption ?? null;
    }
}
```

```php title="config/pharaonic/files.php"
'model' => \App\Models\Attachment::class,
```

Has Files ignores the global scopes of your model in its own queries, the `files()` relation and the handlers included, so positions, limits and deletes always count every row. Filter in your own queries, or use the handlers' `active()`.

Handlers, the `files()` relation and the events then use `App\Models\Attachment`.

## Basic Usage

### Declare fileables

Use the `HasFiles` concern, implement `HasFilesContract`, and return your fileables from `fileables()`. A fileable holds one file unless you call `multiple()`:

```php title="app/Models/Product.php"
use Illuminate\Database\Eloquent\Model;
use Pharaonic\Laravel\Files\Concerns\HasFiles;
use Pharaonic\Laravel\Files\Contracts\HasFilesContract;
use Pharaonic\Laravel\Files\Definitions\File;

class Product extends Model implements HasFilesContract
{
    use HasFiles;

    protected $fillable = ['name', 'cover', 'gallery', 'attachments'];

    public function fileables(): array
    {
        return [
            File::make('cover')->images(),
            File::make('gallery')->images()->multiple()->maxFiles(20),
            File::make('attachments')->multiple(),
        ];
    }
}
```

`HasFiles` overrides none of your model's methods: it saves and detaches files through model events. List the fileables you mass assign in `$fillable`, or set `$guarded = []`. With any other `$guarded`, Laravel only fills real columns, so the files are dropped.

Names start with a letter and contain letters, digits and underscores. A name cannot be one of the model's attributes, casts, accessors, relations or methods (`files` and `file` included), and each name is declared once.

### Save files with the model

Assign files like attributes. They are checked before the model is written and saved right after it:

```php title="app/Http/Controllers/ProductController.php"
$product = Product::create([
    'name' => $request->input('name'),
    'cover' => $request->file('cover'),
    'gallery' => $request->file('gallery', []),
]);

$product->update(['cover' => $request->file('cover')]);
```

A single fileable takes one file, and a multiple fileable takes a list. `null` empties either. See [Saving With Models](#saving-with-models) for every case.

### Read files

`file()` always returns the fileable's handler, even when it is empty:

```php
$product->file('cover')->url;        // the file URL, or the fallback
$product->file('cover')->exists();   // true
$product->file('cover')->get();      // Pharaonic\Laravel\Files\Models\File, or null

$product->file('gallery')->get();    // Eloquent Collection, ordered by position
$product->file('gallery')->count();  // 3
$product->file('gallery')->first()?->url;

foreach ($product->file('gallery') as $image) {
    echo $image->url;
}
```

### Change files directly

Handlers write at once, on a saved model:

```php
$product->file('gallery')->add($request->file('photo'));
$product->file('gallery')->findOrFail($id)->disable();
$product->file('cover')->remove();
```

:::info What files can you give?
An `Illuminate\Http\UploadedFile`, such as `$request->file('cover')`, or an `Upload` model you already stored. Paths, URLs, ids and hashes are refused, so a request can never point Has Files at a file on your server.
:::

## Definitions

`File::make()` returns an untyped definition. Pick a type to restrict the accepted files and unlock that type's processing:

```php title="app/Models/Product.php"
public function fileables(): array
{
    return [
        File::make('cover')->images(),
        File::make('intro')->videos(),
        File::make('podcasts')->audios()->multiple(),
        File::make('manual')->documents()->accepts('application/pdf'),
        File::make('archives')->archives()->multiple(),
        File::make('attachments')->multiple(),
    ];
}
```

| Selector | Accepts | Returns |
| --- | --- | --- |
| `images()` | JPEG, PNG, GIF, WebP, BMP and AVIF | `Definitions\Image` |
| `videos()` | Any `video/*` type | `Definitions\Video` |
| `audios()` | Any `audio/*` type | `Definitions\Audio` |
| `documents()` | PDF, Word, Excel, PowerPoint, OpenDocument, RTF, plain text and CSV | `Definitions\Document` |
| `archives()` | ZIP, 7z, RAR, tar, gzip, bzip2 and xz | `Definitions\Archive` |
| `mixed()` | The types you list | `Definitions\MixedFile` |
| none | Any type | `Definitions\File` |

A type is selected once: `Image` has no `videos()` method, and video settings do not exist on images. The type lists do not overlap, so every file belongs to one type at most.

:::warning SVG is not an image type
SVG files can carry scripts, so `images()` does not accept them. To store SVG logos, use an untyped fileable with `accepts('image/svg+xml')` and serve them through the Uploader's file route, which downloads SVG instead of rendering it.
:::

### Shared settings

Every definition has these settings, in any order, before or after the type:

| Method | Description |
| --- | --- |
| `multiple()` / `single()` | Hold an ordered list of files, or one file (the default) |
| `maxSize(int $bytes)` | The largest file accepted |
| `maxFiles(int $count)` | The most files a multiple fileable holds, active or not |
| `accepts(string ...$mimes)` | Accept only these MIME types: `application/pdf` or `image/*` |
| `rules(array\|string $rules)` | Laravel validation rules for new uploaded files |
| `validateUsing(Closure $callback)` | A check receiving the file (UploadedFile or Upload) and the model; return `false` or throw to reject it |
| `authorizeReuse(Closure $callback)` | Decide whether an existing Upload may be attached; receives the Upload and the model |
| `disk(string)`, `path(string)`, `visibility(string)` | Where new uploads are stored (`public` or `private`) |
| `allowDuplicates()` | Allow the same Upload twice in this fileable |
| `fallback(string\|Closure $url)` | The URL a single fileable shows when empty |
| `keepUploads()` | Never delete the uploads this fileable created |
| `keepReplacedUploads(bool $keep = true)` | Keep the upload of a replaced file, unlinked from the model; without a call, the `keep_replaced_uploads` config decides |
| `appendOnUpdate()` / `replaceOnUpdate()` | What a list given to `update()` does (replace by default) |

```php
File::make('gallery')->images()->multiple()->maxFiles(20)->maxSize(5 * 1024 * 1024)
    ->disk('s3')->path('products')->visibility('public');
```

### How limits combine

Limits only add up, they never loosen each other:

1. The Uploader's own limits, such as `max_pixels`, always apply.
2. The type accepts its own MIME list, and the fileable's `accepts()` narrows it.
3. In a mixed fileable, each type's `accepts()` narrows it again, and both the fileable's and the type's `maxSize()` must pass.

`accepts()` on a typed definition must stay inside that type: `File::make('manual')->images()->accepts('application/pdf')` is refused.

### Mixed fileables

`mixed()` lists the accepted types explicitly. Each type takes an optional callback, which receives that type's definition for its own limits and processing:

```php title="app/Models/Product.php"
use Pharaonic\Laravel\Files\Definitions\Document;
use Pharaonic\Laravel\Files\Definitions\Image;
use Pharaonic\Laravel\Files\Definitions\Video;

File::make('media')->multiple()->maxFiles(15)->mixed()
    ->images(fn (Image $images) => $images->maxFiles(10)->compress(80))
    ->videos(fn (Video $videos) => $videos->maxFiles(3)->compress(crf: 23))
    ->documents(fn (Document $documents) => $documents->accepts('application/pdf')),
```

All files of a mixed fileable share one order. A file whose type is not listed is refused. A callback sets limits, accepted types, rules and processing; settings of the whole fileable, such as `multiple()`, `disk()` or `fallback()`, throw a `LogicException` there. A mixed fileable with no type is invalid.

### Invalid definitions

Definitions are checked the first time the model reads or sets an attribute, and again on every write. Invalid names, conflicting names, `maxFiles()` without `multiple()`, an `accepts()` outside the type, and conflicting processing settings (such as `compress()` with `bitrate()` on a video) throw an `InvalidArgumentException` naming the fileable.

`fileables()` runs again for every write, so settings may depend on the model or the config. The names are read once per model instance and must not depend on its attributes.

## Processing

Files are stored exactly as they are uploaded. Choosing a type only restricts the accepted files; it never processes them. Processing happens only when a definition asks for it, and the [Uploader](https://pharaonic.dev/packages/laravel/uploader) does the work while the file uploads.

```php
File::make('avatar')->images();                                  // stored as uploaded, no thumbnail
File::make('avatar')->images()->thumbnail();                     // thumbnail of the Uploader's configured size
File::make('gallery')->images()->multiple()->thumbnail(width: 400);
```

### Images

| Method | Description |
| --- | --- |
| `thumbnail(?int $width = null, ?int $height = null, bool $ratio = true)` | Make a thumbnail; without a size, the Uploader's `thumbnail` config size (400 pixels wide by default) |
| `withoutThumbnail()` | Cancel an earlier `thumbnail()`, keeping the other processing |
| `resize(?int $maxWidth = null, ?int $maxHeight = null, bool $upscale = false)` | Fit into a maximum size, keeping the ratio; never enlarged unless `$upscale` |
| `compress(int $quality)` | Re-encode at a quality from 1 to 100 (JPEG, WebP and AVIF) |
| `convert(string $format)` | Store as `jpg`, `png`, `gif`, `webp` or `avif` |
| `preserveOriginal(bool $preserve = true)` | Keep the original upload, reachable through `$file->upload->original` |

```php title="app/Models/Product.php"
File::make('gallery')->images()->multiple()->maxFiles(20)
    ->resize(maxWidth: 1920)->convert('webp')->compress(80)->thumbnail(width: 400),
```

Image processing runs while the file uploads, through Intervention Image. EXIF orientation is applied to JPEG photos, transparency turns white when converting to JPEG, and animated GIF or WebP files are stored unchanged with the `skipped` status. The output size depends on the image and the format, so `compress()` never promises a file size.

### Videos

| Method | Description |
| --- | --- |
| `thumbnail(?float $at = null, ?int $width = null)` | A thumbnail from the frame at `$at` seconds; past the end, a frame near the end is used |
| `withoutThumbnail()` | Cancel an earlier `thumbnail()` |
| `resize(?int $maxWidth = null, ?int $maxHeight = null)` | Fit into a maximum size, keeping the ratio |
| `compress(int $crf)` | Constant rate factor: lower is better quality |
| `bitrate(int $kilobits)` | A target bitrate, instead of `compress()` |
| `codec(string $codec)` | `h264`, `h265`, `vp9` or `av1` |
| `convert(string $format)` | `mp4`, `mov`, `mkv` or `webm`, matching the codec |
| `frameRate(float $fps)` | 1 to 240 frames per second |
| `mute(bool $mute = true)` | Remove the audio track |
| `preserveOriginal(bool $preserve = true)` | Keep the original upload |
| `synchronous(?bool $synchronous = true)` | Process during the upload instead of on the queue |

```php title="app/Models/Product.php"
File::make('intro')->videos()->thumbnail(at: 3, width: 400)->compress(crf: 23)->codec('h264')->convert('mp4'),
```

### Audio

| Method | Description |
| --- | --- |
| `convert(string $format)` | `mp3`, `aac`, `m4a`, `ogg`, `opus`, `wav` or `flac` |
| `bitrate(int $kilobits)` | 8 to 512 kbit/s, not for `wav` or `flac` |
| `sampleRate(int $hertz)` | A standard rate such as 44100 or 48000 |
| `channels(int $channels)` | 1 to 8 channels |
| `preserveOriginal(bool $preserve = true)` | Keep the original upload |
| `synchronous(?bool $synchronous = true)` | Process during the upload instead of on the queue |

An audio fileable accepts `audio/*` files only, even though FFmpeg could read the sound of a video.

### FFmpeg and the queue

Video and audio processing needs FFmpeg and FFprobe. Install them on every server that uploads or runs the queue, and set their paths in the Uploader's `ffmpeg` config when they are not on the `PATH`:

```bash title="Terminal" no-line-numbers
sudo apt-get install ffmpeg
```

Processing is queued after the upload's transaction commits, so run a worker on the queue set in the Uploader's `processing` config:

```bash title="Terminal" no-line-numbers
php artisan queue:work
```

The file is attached at once, and its Upload holds the original until the job replaces it:

| `$file->upload->status` | Meaning |
| --- | --- |
| `null` | No processing was asked for |
| `pending` | Waiting for the queue; the original is served |
| `processing` | A worker is processing it |
| `completed` | The processed file replaced the original |
| `failed` | Processing failed; the original is still served |
| `skipped` | Processing did not apply, such as resizing an animated image |

An attachment's `is_active` is yours and is independent of the status: a pending video is still active. Listen to the Uploader's `UploadProcessed` and `UploadProcessingFailed` events to react when processing ends, and use `php artisan uploader:process` to retry failed uploads.

:::warning Missing FFmpeg
Asking for video or audio processing without FFmpeg throws the Uploader's `ProcessingUnavailableException` before anything is stored. Plain uploads, without processing, never need FFmpeg.
:::

:::warning Synchronous processing holds the write
With `synchronous()`, or the Uploader's `processing.sync`, FFmpeg runs inside the Has Files write: its transaction stays open and the owner row stays locked until processing ends. Other writes to that model wait meanwhile, and on MySQL they fail once `innodb_lock_wait_timeout` (50 seconds by default) passes. Keep video and audio on the queue, and use synchronous processing only for short files or scripts.
:::

### Existing uploads are never reprocessed

An `Upload` you attach is used as it is: its file, disk, visibility and thumbnail do not change, even when the fileable asks for processing. To get a processed copy, upload the file again through the fileable.

## Saving With Models

Fileables behave like attributes on assignment. When the model saves, Has Files takes the value out of the attributes on `saving`, checks the files before the row is written, and stores them on `saved`, right after the model's own insert or update.

```php
$product = Product::create(['name' => 'Laptop', 'cover' => $image, 'gallery' => $images]);

$product->update(['cover' => $newImage, 'gallery' => $newImages]);

$product->cover = $anotherImage;
$product->gallery = $anotherBatch;
$product->save();
```

### What each value does

| Value | Single fileable | Multiple fileable |
| --- | --- | --- |
| Key left out | Unchanged | Unchanged |
| One file | Replaces the file | Refused |
| A list of files | Refused | Replaces the files (or adds them with `appendOnUpdate()`) |
| `null` | Removes the file | Removes every file |
| `[]` | Refused | Removes every file, also with `appendOnUpdate()` |

A refused value throws an `InvalidArgumentException` on `save()`, before the model row is written. The files themselves are validated at the same point, and again while they are stored, including the files the fileable already has.

### Rules that stay Eloquent's

- **Mass assignment.** `create()`, `update()` and `fill()` respect `$fillable` and `$guarded`: list the fileables in `$fillable`, or set `$guarded = []`. Any other `$guarded` lets Laravel fill real columns only, so the files are dropped. `forceFill()` assigns them anyway.
- **Saving without changes.** A model whose only change is a file still saves: `$product->save()` returns `true`, writes the file and leaves the row and its `updated_at` untouched.
- **Reading.** `$product->file('cover')` shows what is saved. A file you assigned appears only after `save()`.
- **Cancelled saves.** When a `saving` listener returns `false`, nothing is written and the assigned files stay, ready for the next `save()`. A `saving` listener must return nothing or `false`: any other value stops Laravel from calling the listeners after it, Has Files included.
- **Failures.** When a file fails validation, the save stops before the model row is written and the assigned values stay, so you can fix the input and call `save()` once more. A failure while storing comes after the model is written: the files stored so far are deleted, but the model row stays. Wrap the save in `DB::transaction()` when the model and its files must succeed or fail together.
- **Serialization.** Until the model saves, an assigned file sits in its attributes like any other value, so `toArray()`, `toJson()` and a clone see it. `replicate()` drops it, and after `save()` it is gone from the attributes.

`firstOrCreate()` and `updateOrCreate()` work with fileables in the values, never in the lookup attributes:

```php
Product::firstOrCreate(['name' => 'Laptop'], ['cover' => $image]);
Product::updateOrCreate(['name' => 'Laptop'], ['gallery' => $images]);
```

### Deleting models

A hard delete, or `forceDelete()`, detaches every file of the model right after the row is deleted, including files of fileables you no longer declare. A soft delete keeps them, and `restore()` brings the model back with its files. To detach them on a soft delete too, turn on `detach_on_soft_delete`:

```php title="config/pharaonic/files.php"
'detach_on_soft_delete' => true,
```

A file detached that way does not come back with `restore()`. The uploads Has Files created are deleted after the commit, once no other file uses them.

### Replacing files

Replacing a file, by assigning a new one, `update()`, or a handler's `set()`, detaches the old file and deletes the upload Has Files created for it. To keep that upload, unlinked from the model, set `keep_replaced_uploads` to `true`, or call `keepReplacedUploads()` on a fileable; the fileable's choice wins over the config:

```php
File::make('contract')->documents()->keepReplacedUploads();
File::make('avatar')->images()->keepReplacedUploads(false);
```

Removing a file with `remove()`, `clear()` or `null` still deletes its upload; use `keepUploads()` to keep every upload of a fileable.

`replicate()` copies neither the files nor the assigned values.

### Transactions

File writes run in a transaction on the files connection, nested in yours when you open one. The model's own insert or update is not part of that transaction unless you open one around it. Events and upload deletions wait for the outermost commit; when your transaction rolls back, the files stored inside it are deleted and no event is dispatched.

```php
DB::transaction(function () use ($product, $request) {
    $product->update(['name' => $request->input('name')]);
    $product->file('gallery')->addMany($request->file('photos'));
});
```

:::warning What bypasses the lifecycle
Query builder writes run no model code: `Product::query()->delete()`, `update()`, `insert()`, `upsert()` and `MassPrunable` leave the files as they are. Delete models one by one, or detach their files first.
:::

Uploads stored on a database connection other than the files connection are deleted when the files transaction rolls back, but the two connections never share one atomic transaction.

## Single Files

A single fileable returns a `Pharaonic\Laravel\Files\Fileables\SingleFile`. Writes need a saved model; to give a file to a new model, assign it and call `save()`.

```php
$file = $product->file('cover')->set($request->file('cover')); // replaces the current file

$product->file('cover')->get();       // Models\File, or null
$product->file('cover')->exists();    // true
$product->file('cover')->isActive();  // true

$product->file('cover')->disable();
$product->file('cover')->enable();
$product->file('cover')->toggle();
$product->file('cover')->setMeta(['alt' => 'Front view']);
$product->file('cover')->remove();
```

### Read-only properties

The handler reads its file's properties. They are `null` when there is no file, except `url`, which falls back to the fileable's `fallback()`:

```php
$product->file('cover')->url;        // "https://example.com/file/Xk2…jpg"
$product->file('cover')->thumbnail;  // the thumbnail URL, or null
$product->file('cover')->meta;       // stdClass, or null
$product->file('cover')->size;       // 48213
$product->file('cover')->mime;       // "image/jpeg"
$product->file('cover')->extension;  // "jpg"
$product->file('cover')->type;       // "image"
$product->file('cover')->is_active;  // true
$product->file('cover')->id;         // the attachment id
```

Any other property throws an `InvalidArgumentException`. Each read loads the file, so read it once when you need several values:

```php
$cover = $product->file('cover')->get();

echo $cover?->url;
echo $cover?->thumbnail;
```

### When the fileable is empty

| Call | Result |
| --- | --- |
| `get()` | `null` |
| `exists()`, `isActive()` | `false` |
| `enable()`, `disable()`, `toggle()`, `remove()` | Nothing happens |
| `setMeta()` | Throws `ModelNotFoundException` |
| `url` | The fallback, or `null` |
| `temporaryUrl()` | `null` |

### Fallbacks

`fallback()` gives a single fileable a URL to show when it is empty. It is a presentation value only: `exists()` stays `false`.

```php title="app/Models/User.php"
File::make('avatar')->images()->fallback(fn (User $user) => 'https://ui-avatars.com/api/?name='.urlencode($user->name)),
```

### Temporary URLs

`url` already returns a temporary URL for private files on S3. Ask for one with your own expiry:

```php
$product->file('manual')->temporaryUrl(10); // valid for 10 minutes
```

The disk must support temporary URLs; the Uploader throws a `RuntimeException` otherwise.

## Multiple Files

A multiple fileable returns a `Pharaonic\Laravel\Files\Fileables\MultipleFiles`. Its files are always ordered, from position 1, and it is `Countable` and iterable.

### Reading

```php
$product->file('gallery')->get();    // Eloquent Collection of Models\File, by position
$product->file('gallery')->exists(); // true
$product->file('gallery')->count();  // 3
$product->file('gallery')->first();
$product->file('gallery')->last();
$product->file('gallery')->at(2);    // the file at position 2, or null

$product->file('gallery')->find($id);       // by attachment id, or null
$product->file('gallery')->findOrFail($id); // throws ModelNotFoundException
```

Ids are attachment ids (`$file->id`), never upload ids. `find()` only finds files of this fileable of this model, so an id from a request cannot reach another model's files.

### Views

These methods return a read-only view of the fileable. Views read a subset and never renumber positions; calling a write method on one throws a `LogicException`:

```php
$product->file('gallery')->active()->get();
$product->file('gallery')->inactive()->count();
$product->file('gallery')->reverse()->get();          // last position first
$product->file('media')->images()->active()->get();
$product->file('media')->videos()->first();
$product->file('media')->documents()->get();
```

`images()`, `videos()`, `audios()`, `documents()` and `archives()` filter by each file's detected type, on any multiple fileable. `at()` on a view returns the file at that stored position only when it matches the view.

### Adding and replacing

```php
$product->file('gallery')->add($photo);                 // at the end
$product->file('gallery')->add($photo, position: 2);    // the files from 2 move down
$product->file('gallery')->prepend($photo);             // at position 1
$product->file('gallery')->addMany($photos);            // at the end, in order
$product->file('gallery')->addMany($photos, position: 1);
$product->file('gallery')->set($photos);                // replaces every file
$product->file('gallery')->clear();                     // removes every file
```

`add()` and `prepend()` return the new `Models\File`; `addMany()` and `set()` return a collection. The whole batch is validated first, together with the files already attached, so a batch that would pass `maxFiles()` adds nothing. `set([])` clears the fileable.

### Ordering

```php
$product->file('gallery')->reorder([5, 3, 1, 2, 4]);

$image = $product->file('gallery')->findOrFail(3);
$image->moveTo(2);
$image->moveUp();
$image->moveDown();
$image->moveToFirst();
$image->moveToLast();
```

`reorder()` takes every attachment id of the fileable exactly once. A missing, repeated or foreign id throws an `InvalidArgumentException` and changes nothing. A position outside 1 to the number of files throws too; moving the first file up, or the last down, changes nothing. Removing a file moves the following files up, so positions stay 1, 2, 3… Disabled files keep their positions.

Ordering methods on the file of a single fileable throw a `LogicException`.

### Activation

```php
$product->file('gallery')->disable();                    // every file
$product->file('gallery')->enable();                     // every file, inactive ones included
$product->file('gallery')->findOrFail($id)->disable();   // one file
$product->file('gallery')->findOrFail($id)->toggle();
```

Activation is stored per attachment, so one upload can be active on one model and inactive on another. Disabling hides nothing by itself: filter with `active()` where you show files, and protect private files with the disk's visibility. New files are active.

### Concurrent requests

Every write locks the owner's row first, even when the fileable is empty, so two requests adding files to one product take turns: the order stays contiguous and `maxFiles()` holds. A unique index on owner, name and position backs the lock.

## Validation and Uploads

### Validation errors

A file that fails a fileable's checks throws Laravel's `Illuminate\Validation\ValidationException`, so a form request redirects back with the errors and an API returns 422. The keys are the fileable name, with the file's index for multiple fileables:

```php
// ['cover' => ['The cover must be a file of an accepted type.']]
// ['gallery.2' => ['The gallery.2 may not be greater than 2048 kilobytes.']]
// ['gallery' => ['The gallery may not have more than 20 files.']]
// ['media' => ['The media may not have more than 3 video files.']]
```

The messages ship in English (`en`) and Arabic (`ar`) and follow the application locale. Publish them with `php artisan vendor:publish --tag=files-translations` to change them or add another language; they live under `files::validation`.

The type is detected from the file's content, never from its name or the browser's MIME type: a PHP script named `photo.jpg` is refused by `images()`. Keep validating requests in your form requests too. Has Files checks what it stores; it does not replace your input validation.

### Reusing uploads

Attach an `Upload` you already stored, for example one picked in a media library:

```php
use Pharaonic\Laravel\Uploader\Models\Upload;

$upload = Upload::query()->findOrFail($request->input('upload_id'));
$this->authorize('use', $upload);

$product->file('gallery')->add($upload);
```

The upload is checked like a new file (type, size and limits, from its stored MIME type and size), but it is attached as it is: it is never reprocessed or moved. Looking it up and authorizing it are your job; add a check every time it is attached with `authorizeReuse()`:

```php title="app/Models/Product.php"
File::make('gallery')->images()->multiple()
    ->authorizeReuse(fn (Upload $upload, Product $product) => $upload->created_at->isAfter(now()->subDay())),
```

A fileable refuses the same upload twice unless you call `allowDuplicates()`.

### Who deletes the uploads

| Upload | When its last file is removed |
| --- | --- |
| Created by Has Files from an UploadedFile | Deleted after the commit, unless the fileable has `keepUploads()` |
| Created by Has Files, and its file was replaced | Deleted too, unless `keepReplacedUploads()` or the `keep_replaced_uploads` config keeps it |
| An existing Upload you attached | Kept |

The deletion checks every file of every model first: an upload attached somewhere else stays. While a file uses an upload, deleting the upload throws `Pharaonic\Laravel\Files\Exceptions\UploadInUseException`, and the database refuses it too when the files and uploads tables share a connection. Remove the files first, then delete the upload. The check counts every file row, also rows a global scope of your custom file model hides.

When the uploads table is on another connection than the files table, there is no foreign key, so Has Files opens a transaction on the uploads connection around each write: a reused upload stays locked until its file is committed, and a removal that comes at the same moment waits for it.

Giving a fileable the upload it already holds, as in `$product->update(['cover' => $product->file('cover')->get()->upload])`, keeps the upload owned, so it is still deleted once it is really replaced.

### Private files

Store a fileable on a private disk, or with `visibility('private')` on S3, and `url` returns the Uploader's URL for it: a temporary URL on S3, or the hashed file route on local disks. Disabling a file does not protect its URL. Check access in your controller before you hand out a URL, and use `temporaryUrl()` with a short expiry for sensitive files.

## Events and Queries

### Events

Has Files dispatches these events after the transaction of the change commits. A change that rolls back dispatches nothing.

| Event | Dispatched | Properties |
| --- | --- | --- |
| `Events\FileAttached` | Once per file added by `set()`, `add()`, `addMany()`, `prepend()` or a save | `$owner`, `$file` |
| `Events\FileDetached` | Once per file removed, replaced, cleared, or detached by a hard delete | `$owner`, `$file` |
| `Events\FileActivated` | Once per file whose activation changed to active | `$owner`, `$file` |
| `Events\FileDeactivated` | Once per file whose activation changed to inactive | `$owner`, `$file` |
| `Events\FilesReordered` | Once per `reorder()` or move that changed the order | `$owner`, `$name` |

The namespace is `Pharaonic\Laravel\Files\Events`. Processing events, `UploadProcessed` and `UploadProcessingFailed`, belong to the Uploader.

```php title="app/Providers/EventServiceProvider.php"
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;
use Pharaonic\Laravel\Files\Events\FileAttached;

Event::listen(FileAttached::class, function (FileAttached $event) {
    Log::info('File attached', ['fileable' => $event->file->name, 'file' => $event->file->id]);
});
```

### The files relation

`files()` is a `morphMany` relation to every attached file of the model, of every fileable. It always loads each file's upload and the upload's thumbnail with it, so eager loading `files` is enough when you list models:

```php
$products = Product::with('files')->get();   // files, uploads and thumbnails: three queries

foreach ($products as $product) {
    echo $product->file('cover')->url;                  // no query
    echo $product->file('gallery')->active()->count();  // no query
}
```

Fileables read the loaded relation instead of querying. A write through Has Files unloads the relation, so the next read sees the change.

### Query scopes

```php
Product::whereHasFile('cover')->get();               // products with a cover
Product::whereHasFile('gallery', true)->get();       // with an active gallery file
Product::whereDoesntHaveFile('cover')->get();        // products without one
```

The scopes are subqueries on the files table, which shares the owners' connection.

### JSON and API resources

Handlers are never added to `toArray()` or `toJson()`. The `files` relation appears there only when you load it, without its `upload` (which carries the disk and path). Choose what you expose in an API resource; see [Examples](#examples).

## API Reference

### HasFiles concern

`Pharaonic\Laravel\Files\Concerns\HasFiles`, used with `Pharaonic\Laravel\Files\Contracts\HasFilesContract`.

| Method | Description | Returns |
| --- | --- | --- |
| `fileables()` | Your fileable definitions (empty by default) | `array` |
| `file(string $name)` | The handler of a fileable | `SingleFile\|MultipleFiles` |
| `files()` | Every attached file of the model | `MorphMany` |
| `whereHasFile(string $name, bool $activeOnly = false)` | Scope: models with a file in the fileable | `Builder` |
| `whereDoesntHaveFile(string $name)` | Scope: models without one | `Builder` |

Assigning `$model->{name}` keeps the value in the attributes until `save()`, where it is taken out before the row is written. The concern overrides no model method: it registers an observer on `saving`, `saved`, `deleted` and `replicating`, so it works next to any other trait.

### Definitions

`Definitions\File::make(string $name)` returns a `File`. The type selectors on `File` are `images()`, `videos()`, `audios()`, `documents()`, `archives()` and `mixed()`. The shared settings are listed in [Definitions](#definitions), and the processing methods of `Image`, `Video` and `Audio` in [Processing](#processing). `MixedFile` adds `images()`, `videos()`, `audios()`, `documents()` and `archives()`, each taking an optional callback.

### SingleFile

| Method | Description | Returns |
| --- | --- | --- |
| `set(UploadedFile\|Upload $input)` | Attach a file, replacing the current one | `Models\File` |
| `get()` | The file | `?Models\File` |
| `exists()` | Whether there is a file | `bool` |
| `isActive()` | Whether there is an active file | `bool` |
| `enable()`, `disable()`, `toggle()` | Change the activation; nothing happens when empty | `SingleFile` |
| `setMeta(?array $meta)` | Replace the metadata; throws when empty | `SingleFile` |
| `remove()` | Detach the file | `SingleFile` |
| `temporaryUrl(?int $minutes = null)` | A temporary URL | `?string` |
| `name()` | The fileable name | `string` |

Properties: `id`, `url`, `thumbnail`, `meta`, `size`, `mime`, `extension`, `type`, `is_active`.

### MultipleFiles

| Method | Description | Returns |
| --- | --- | --- |
| `add(UploadedFile\|Upload $input, ?int $position = null)` | Add a file at the end or at a position | `Models\File` |
| `addMany(array $inputs, ?int $position = null)` | Add files in order | `Collection` |
| `prepend(UploadedFile\|Upload $input)` | Add a file at position 1 | `Models\File` |
| `set(array $inputs)` | Replace every file | `Collection` |
| `clear()` | Remove every file | `MultipleFiles` |
| `enable()`, `disable()` | Change the activation of every file | `MultipleFiles` |
| `reorder(array $ids)` | Order by a list of every attachment id | `MultipleFiles` |
| `get()` | The files, by position | `Collection` |
| `exists()`, `count()` | Whether there are files, how many | `bool`, `int` |
| `first()`, `last()`, `at(int $position)` | One file | `?Models\File` |
| `find(int\|string $id)`, `findOrFail(int\|string $id)` | A file by attachment id | `?Models\File`, `Models\File` |
| `active()`, `inactive()`, `reverse()` | Read-only views | `MultipleFiles` |
| `images()`, `videos()`, `audios()`, `documents()`, `archives()` | Read-only views of one type | `MultipleFiles` |
| `name()` | The fileable name | `string` |

### Models\File

| Column | Description |
| --- | --- |
| `id` | The attachment id |
| `fileable_type`, `fileable_id` | The owner, with your morph map |
| `upload_id` | The Uploader upload |
| `name` | The fileable name |
| `position` | From 1; always 1 in a single fileable |
| `is_active` | `true` by default |
| `owns_upload` | Whether Has Files created the upload |
| `meta` | A JSON object or `null`, read as `stdClass` |
| `created_at`, `updated_at` | Timestamps |

| Accessor or relation | Description |
| --- | --- |
| `url`, `thumbnail` | URLs from the upload, `null` without one |
| `mime`, `size`, `extension` | From the upload |
| `type` | `image`, `video`, `audio`, `document`, `archive` or `null` |
| `upload` | The `Upload` (hidden from JSON) |
| `fileable` | The owner model (hidden from JSON) |

| Method | Description | Returns |
| --- | --- | --- |
| `isActive()` | The activation | `bool` |
| `enable()`, `disable()`, `toggle()` | Change the activation | `static` |
| `setMeta(?array $meta)` | Replace the metadata: `[]` stores `{}`, `null` removes it, a list is refused | `static` |
| `remove()` | Detach the file; the following ones move up | `void` |
| `moveTo(int $position)`, `moveUp()`, `moveDown()`, `moveToFirst()`, `moveToLast()` | Move a file of a multiple fileable | `static` |
| `temporaryUrl(?int $minutes = null)` | A temporary URL | `?string` |

### Exceptions

| Exception | Thrown when |
| --- | --- |
| `Illuminate\Validation\ValidationException` | A file fails the fileable's type, size, count, duplicate, rule or authorization checks |
| `InvalidArgumentException` | An invalid definition, an unknown fileable, a value of the wrong shape, an invalid position or order |
| `LogicException` | A write on an unsaved model or a view, ordering a single fileable, or a connection other than the owner's |
| `Illuminate\Database\Eloquent\ModelNotFoundException` | `findOrFail()` finds nothing, `setMeta()` on an empty single fileable, or moving a file removed since it was read |
| `Exceptions\UploadInUseException` | Deleting an upload a file still uses |

## Examples

### 1. A product form with a cover and a gallery

The form request validates the input, and the model saves the files with the product.

- ===Model

  ```php title="app/Models/Product.php"
  use Illuminate\Database\Eloquent\Model;
  use Pharaonic\Laravel\Files\Concerns\HasFiles;
  use Pharaonic\Laravel\Files\Contracts\HasFilesContract;
  use Pharaonic\Laravel\Files\Definitions\File;

  class Product extends Model implements HasFilesContract
  {
      use HasFiles;

      protected $fillable = ['name', 'cover', 'gallery'];

      public function fileables(): array
      {
          return [
              File::make('cover')
                  ->images()
                  ->thumbnail(width: 400)
                  ->fallback('/images/no-cover.png'),

              File::make('gallery')
                  ->images()
                  ->multiple()
                  ->maxFiles(20)
                  ->resize(maxWidth: 1920)
                  ->convert('webp')
                  ->compress(80)
                  ->thumbnail(width: 400),
          ];
      }
  }
  ```

- ===Request

  ```php title="app/Http/Requests/StoreProductRequest.php"
  public function rules(): array
  {
      return [
          'name' => ['required', 'string', 'max:255'],
          'cover' => ['nullable', 'image', 'max:5120'],
          'gallery' => ['nullable', 'array', 'max:20'],
          'gallery.*' => ['image', 'max:5120'],
      ];
  }
  ```

- ===Controller

  ```php title="app/Http/Controllers/ProductController.php"
  public function store(StoreProductRequest $request)
  {
      $product = Product::create($request->validated());

      return redirect()->route('products.show', $product);
  }
  ```

### 2. A disk and a directory for each fileable

`disk()`, `path()` and `visibility()` choose where the new uploads of a fileable are stored. They apply to every file of that fileable; anything not set falls back to the Uploader's config, and `path()` is relative to the Uploader's base path.

```php title="app/Models/Product.php"
use Pharaonic\Laravel\Files\Definitions\File;

public function fileables(): array
{
    return [
        File::make('cover')
            ->images()
            ->disk('s3')
            ->path('products/covers')
            ->visibility('public'),

        File::make('invoices')
            ->documents()
            ->multiple()
            ->disk('local')
            ->path('invoices'),
    ];
}
```

The order of the calls does not matter: `images()` and `documents()` keep the settings made before them.

Definitions are read again on every call, so a path may depend on the model:

```php
File::make('invoices')
    ->documents()
    ->multiple()
    ->path('invoices/'.$this->getKey()),
```

A new model is inserted before its files are stored, so its key is already set.

A mixed fileable has one disk, path and visibility for all its types. Setting them inside a type's callback throws a `LogicException`.

:::warning Two classes named File
Fileables are declared with `Pharaonic\Laravel\Files\Definitions\File`. The attached rows are `Pharaonic\Laravel\Files\Models\File`. Alias one of them when a class uses both:

```php
use Pharaonic\Laravel\Files\Definitions\File;
use Pharaonic\Laravel\Files\Models\File as FileModel;
```
:::

To store one file somewhere else, upload it yourself and attach the `Upload`. It then counts as a reused upload: removing it from the fileable does not delete it.

```php
use Pharaonic\Laravel\Uploader\Facades\Uploader;

$upload = Uploader::upload($request->file('cover'), [
    'disk' => 's3',
    'path' => 'campaigns/2026',
]);

$product->file('cover')->set($upload);
```

### 3. Public and admin API resources

Expose only what each client needs. Never return the upload's disk, path or original name.

- ===Public

  ```php title="app/Http/Resources/ProductResource.php"
  public function toArray($request)
  {
      return [
          'id' => $this->id,
          'name' => $this->name,
          'cover' => $this->file('cover')->url,
          'gallery' => $this->file('gallery')
              ->active()
              ->get()
              ->map(fn ($image) => [
                  'url' => $image->url,
                  'thumbnail' => $image->thumbnail,
                  'alt' => $image->meta->alt ?? null,
              ]),
      ];
  }
  ```

- ===Admin

  ```php title="app/Http/Resources/Admin/ProductResource.php"
  public function toArray($request)
  {
      return [
          'id' => $this->id,
          'name' => $this->name,
          'gallery' => $this->file('gallery')
              ->get()
              ->map(fn ($image) => [
                  'id' => $image->id,
                  'position' => $image->position,
                  'is_active' => $image->is_active,
                  'url' => $image->url,
                  'meta' => $image->meta,
                  'size' => $image->size,
                  'status' => $image->upload->status ?? null,
              ]),
      ];
  }
  ```

Load the files once for a list:

```php
$products = Product::query()
    ->with('files')
    ->paginate();

return ProductResource::collection($products);
```

On S3, `url` is already a temporary URL for private files; call `$image->temporaryUrl(5)` for a shorter expiry.

### 4. Sorting and hiding gallery images

A drag-and-drop gallery sends the full order of attachment ids:

```php title="app/Http/Controllers/ProductGalleryController.php"
public function reorder(Request $request, Product $product)
{
    $request->validate([
        'order' => ['required', 'array'],
        'order.*' => ['integer'],
    ]);

    $product->file('gallery')->reorder($request->input('order'));

    return response()->noContent();
}

public function toggle(Product $product, int $file)
{
    $product->file('gallery')
        ->findOrFail($file)
        ->toggle();

    return back();
}
```

The primary image is the first active one:

```php
$primary = $product->file('gallery')
    ->active()
    ->first();
```

### 5. A media list with images, videos and PDFs

```php title="app/Models/Lesson.php"
public function fileables(): array
{
    return [
        File::make('media')
            ->multiple()
            ->maxFiles(15)
            ->mixed()
            ->images(fn (Image $images) => $images
                ->maxFiles(10)
                ->thumbnail())
            ->videos(fn (Video $videos) => $videos
                ->maxFiles(3)
                ->thumbnail(at: 2)
                ->compress(crf: 26))
            ->documents(fn (Document $documents) => $documents
                ->accepts('application/pdf')),
    ];
}
```

```blade title="resources/views/lessons/show.blade.php"
@foreach ($lesson->file('media')->active() as $item)
    @if ($item->type === 'image')
        <img src="{{ $item->url }}" alt="{{ $item->meta->alt ?? '' }}">
    @elseif ($item->type === 'video')
        <video src="{{ $item->url }}" poster="{{ $item->thumbnail }}" controls></video>
    @else
        <a href="{{ $item->url }}">{{ $item->meta->title ?? 'Download' }}</a>
    @endif
@endforeach
```

The videos play their original until the queue finishes processing them.

### 6. Picking an upload from a media library

```php title="app/Http/Controllers/ProductCoverController.php"
public function update(Request $request, Product $product)
{
    $upload = Upload::query()
        ->findOrFail($request->input('upload_id'));
    $this->authorize('use', $upload);

    $product->file('cover')->set($upload);
    $product->file('cover')->setMeta(['alt' => $request->input('alt')]);

    return back();
}
```

The library keeps its upload: removing the cover later never deletes it.

## Troubleshooting

### Files passed to create() are ignored

The fileable is not mass assignable. Add its name to `$fillable`, or set `$guarded = []`: with any other `$guarded`, Laravel fills only real columns. `forceFill()` assigns it anyway.

### Files assigned to a model are not saved

A `saving` listener of yours returns a value other than `null` or `false`. Laravel stops calling the remaining `saving` listeners as soon as one returns a value, so Has Files never sees the files and the save fails on an unknown column. Return nothing from `saving` listeners, or `false` to cancel.

### "The [cover] fileable holds one file"

A single fileable got a list, or a multiple fileable got one file. Give a multiple fileable a list (`[$file]`), or use its `add()` method.

### "conflicts with an attribute, cast, accessor, relation or method"

A fileable name is also a column, cast, accessor, relation or method of the model (`files` and `file` are taken by the concern). Rename the fileable, or the model member.

### A valid image is refused

The type comes from the content. Check `$request->file('cover')->getMimeType()`: an SVG, a HEIC photo or a renamed file is not one of the image types. Accept it with an untyped fileable and `accepts()`, or convert it before uploading.

### "Has Files needs both on one connection"

The owner model uses another connection than the files table. Set `connection` in `config/pharaonic/files.php` to the owners' connection, before migrating.

### ProcessingUnavailableException

A definition asks for video or audio processing and FFmpeg or FFprobe is not found, or the image driver cannot write the format. Install FFmpeg, or set `ffmpeg.binary` and `ffmpeg.ffprobe` in the Uploader's config; check GD or Imagick support for WebP and AVIF.

### Videos stay pending

No queue worker runs on the Uploader's processing queue. Start one with `php artisan queue:work`, then run `php artisan uploader:process --apply` to queue the pending uploads again.

### UploadInUseException when deleting an upload

A file still uses it. Remove the files that use it, through their handlers or by deleting their owners, then delete the upload.

### A gallery shows stale files

The model's `files` relation was loaded before another request changed the files. Reload it with `$product->load('files')`, or read the fileable from a fresh model.

### Files remain after deleting models

The models were deleted with a query (`Product::query()->delete()`), which runs no model code. Delete them one by one, or remove their files first.
