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, so every file is an Uploader Upload.
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.
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, 8.1 or 8.2
- Laravel 9.33 or newer within 9.x
pharaonic/laravel-uploader9.1.1 or newer within 9.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
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:
php artisan migrateSet the table, connection and key_type options before you run it: the migration reads them. To copy the migrations into database/migrations instead, publish them:
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:
php artisan vendor:publish --tag=files-configThe validation messages (English and Arabic) publish with --tag=files-translations. The pharaonic and laravel-has-files tags publish everything.
You're all set! Add the HasFiles concern to a model and declare its first fileable in Basic Usage.
#Configuration
The options live under pharaonic.files, published to config/pharaonic/files.php:
1return [2 'model' => \Pharaonic\Laravel\Files\Models\File::class,3 'table' => 'files',4 'connection' => null,5 'key_type' => 'integer',6 'detach_on_soft_delete' => false,7 'keep_replaced_uploads' => false,8];| 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.
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, so the storage and processing defaults are the Uploader's. To change them, publish the Uploader's config:
1php artisan vendor:publish --tag=uploader-configIt 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:
1File::make('cover')2 ->images()3 ->disk('s3') // instead of the Uploader's disk4 ->path('products/covers') // under the Uploader's path5 ->visibility('public'), // instead of the Uploader's visibilityNothing 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). 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:
1namespace App\Models; 2 3use Pharaonic\Laravel\Files\Models\File; 4 5class Attachment extends File 6{ 7 public function caption(): ?string 8 { 9 return $this->meta->caption ?? null;10 }11}1'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():
1use Illuminate\Database\Eloquent\Model; 2use Pharaonic\Laravel\Files\Concerns\HasFiles; 3use Pharaonic\Laravel\Files\Contracts\HasFilesContract; 4use Pharaonic\Laravel\Files\Definitions\File; 5 6class Product extends Model implements HasFilesContract 7{ 8 use HasFiles; 9 10 protected $fillable = ['name', 'cover', 'gallery', 'attachments'];11 12 public function fileables(): array13 {14 return [15 File::make('cover')->images(),16 File::make('gallery')->images()->multiple()->maxFiles(20),17 File::make('attachments')->multiple(),18 ];19 }20}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:
1$product = Product::create([2 'name' => $request->input('name'),3 'cover' => $request->file('cover'),4 'gallery' => $request->file('gallery', []),5]);6 7$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 for every case.
#Read files
file() always returns the fileable's handler, even when it is empty:
1$product->file('cover')->url; // the file URL, or the fallback 2$product->file('cover')->exists(); // true 3$product->file('cover')->get(); // Pharaonic\Laravel\Files\Models\File, or null 4 5$product->file('gallery')->get(); // Eloquent Collection, ordered by position 6$product->file('gallery')->count(); // 3 7$product->file('gallery')->first()?->url; 8 9foreach ($product->file('gallery') as $image) {10 echo $image->url;11}#Change files directly
Handlers write at once, on a saved model:
1$product->file('gallery')->add($request->file('photo'));2$product->file('gallery')->findOrFail($id)->disable();3$product->file('cover')->remove();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:
1public function fileables(): array 2{ 3 return [ 4 File::make('cover')->images(), 5 File::make('intro')->videos(), 6 File::make('podcasts')->audios()->multiple(), 7 File::make('manual')->documents()->accepts('application/pdf'), 8 File::make('archives')->archives()->multiple(), 9 File::make('attachments')->multiple(),10 ];11}| 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.
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) |
1File::make('gallery')->images()->multiple()->maxFiles(20)->maxSize(5 * 1024 * 1024)2 ->disk('s3')->path('products')->visibility('public');#How limits combine
Limits only add up, they never loosen each other:
- The Uploader's own limits, such as
max_pixels, always apply. - The type accepts its own MIME list, and the fileable's
accepts()narrows it. - In a mixed fileable, each type's
accepts()narrows it again, and both the fileable's and the type'smaxSize()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:
1use Pharaonic\Laravel\Files\Definitions\Document;2use Pharaonic\Laravel\Files\Definitions\Image;3use Pharaonic\Laravel\Files\Definitions\Video;4 5File::make('media')->multiple()->maxFiles(15)->mixed()6 ->images(fn (Image $images) => $images->maxFiles(10)->compress(80))7 ->videos(fn (Video $videos) => $videos->maxFiles(3)->compress(crf: 23))8 ->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 does the work while the file uploads.
1File::make('avatar')->images(); // stored as uploaded, no thumbnail2File::make('avatar')->images()->thumbnail(); // thumbnail of the Uploader's configured size3File::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 |
1File::make('gallery')->images()->multiple()->maxFiles(20)2 ->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 |
1File::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:
sudo apt-get install ffmpegProcessing is queued after the upload's transaction commits, so run a worker on the queue set in the Uploader's processing config:
php artisan queue:workThe 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.
Asking for video or audio processing without FFmpeg throws the Uploader's ProcessingUnavailableException before anything is stored. Plain uploads, without processing, never need FFmpeg.
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.
1$product = Product::create(['name' => 'Laptop', 'cover' => $image, 'gallery' => $images]);2 3$product->update(['cover' => $newImage, 'gallery' => $newImages]);4 5$product->cover = $anotherImage;6$product->gallery = $anotherBatch;7$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()andfill()respect$fillableand$guarded: list the fileables in$fillable, or set$guarded = []. Any other$guardedlets 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()returnstrue, writes the file and leaves the row and itsupdated_atuntouched. - Reading.
$product->file('cover')shows what is saved. A file you assigned appears only aftersave(). - Cancelled saves. When a
savinglistener returnsfalse, nothing is written and the assigned files stay, ready for the nextsave(). Asavinglistener must return nothing orfalse: 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 inDB::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 aftersave()it is gone from the attributes.
firstOrCreate() and updateOrCreate() work with fileables in the values, never in the lookup attributes:
1Product::firstOrCreate(['name' => 'Laptop'], ['cover' => $image]);2Product::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:
1'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:
1File::make('contract')->documents()->keepReplacedUploads();2File::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.
1DB::transaction(function () use ($product, $request) {2 $product->update(['name' => $request->input('name')]);3 $product->file('gallery')->addMany($request->file('photos'));4});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().
1$file = $product->file('cover')->set($request->file('cover')); // replaces the current file 2 3$product->file('cover')->get(); // Models\File, or null 4$product->file('cover')->exists(); // true 5$product->file('cover')->isActive(); // true 6 7$product->file('cover')->disable(); 8$product->file('cover')->enable(); 9$product->file('cover')->toggle();10$product->file('cover')->setMeta(['alt' => 'Front view']);11$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():
1$product->file('cover')->url; // "https://example.com/file/Xk2…jpg"2$product->file('cover')->thumbnail; // the thumbnail URL, or null3$product->file('cover')->meta; // stdClass, or null4$product->file('cover')->size; // 482135$product->file('cover')->mime; // "image/jpeg"6$product->file('cover')->extension; // "jpg"7$product->file('cover')->type; // "image"8$product->file('cover')->is_active; // true9$product->file('cover')->id; // the attachment idAny other property throws an InvalidArgumentException. Each read loads the file, so read it once when you need several values:
1$cover = $product->file('cover')->get();2 3echo $cover?->url;4echo $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.
1File::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:
1$product->file('manual')->temporaryUrl(10); // valid for 10 minutesThe 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
1$product->file('gallery')->get(); // Eloquent Collection of Models\File, by position2$product->file('gallery')->exists(); // true3$product->file('gallery')->count(); // 34$product->file('gallery')->first();5$product->file('gallery')->last();6$product->file('gallery')->at(2); // the file at position 2, or null7 8$product->file('gallery')->find($id); // by attachment id, or null9$product->file('gallery')->findOrFail($id); // throws ModelNotFoundExceptionIds 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:
1$product->file('gallery')->active()->get();2$product->file('gallery')->inactive()->count();3$product->file('gallery')->reverse()->get(); // last position first4$product->file('media')->images()->active()->get();5$product->file('media')->videos()->first();6$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
1$product->file('gallery')->add($photo); // at the end2$product->file('gallery')->add($photo, position: 2); // the files from 2 move down3$product->file('gallery')->prepend($photo); // at position 14$product->file('gallery')->addMany($photos); // at the end, in order5$product->file('gallery')->addMany($photos, position: 1);6$product->file('gallery')->set($photos); // replaces every file7$product->file('gallery')->clear(); // removes every fileadd() 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
1$product->file('gallery')->reorder([5, 3, 1, 2, 4]);2 3$image = $product->file('gallery')->findOrFail(3);4$image->moveTo(2);5$image->moveUp();6$image->moveDown();7$image->moveToFirst();8$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
1$product->file('gallery')->disable(); // every file2$product->file('gallery')->enable(); // every file, inactive ones included3$product->file('gallery')->findOrFail($id)->disable(); // one file4$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:
1// ['cover' => ['The cover must be a file of an accepted type.']]2// ['gallery.2' => ['The gallery.2 may not be greater than 2048 kilobytes.']]3// ['gallery' => ['The gallery may not have more than 20 files.']]4// ['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:
1use Pharaonic\Laravel\Uploader\Models\Upload;2 3$upload = Upload::query()->findOrFail($request->input('upload_id'));4$this->authorize('use', $upload);5 6$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():
1File::make('gallery')->images()->multiple()2 ->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.
1use Illuminate\Support\Facades\Event;2use Illuminate\Support\Facades\Log;3use Pharaonic\Laravel\Files\Events\FileAttached;4 5Event::listen(FileAttached::class, function (FileAttached $event) {6 Log::info('File attached', ['fileable' => $event->file->name, 'file' => $event->file->id]);7});#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:
1$products = Product::with('files')->get(); // files, uploads and thumbnails: three queries2 3foreach ($products as $product) {4 echo $product->file('cover')->url; // no query5 echo $product->file('gallery')->active()->count(); // no query6}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
1Product::whereHasFile('cover')->get(); // products with a cover2Product::whereHasFile('gallery', true)->get(); // with an active gallery file3Product::whereDoesntHaveFile('cover')->get(); // products without oneThe 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.
#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, and the processing methods of Image, Video and Audio in 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.
1use Illuminate\Database\Eloquent\Model; 2use Pharaonic\Laravel\Files\Concerns\HasFiles; 3use Pharaonic\Laravel\Files\Contracts\HasFilesContract; 4use Pharaonic\Laravel\Files\Definitions\File; 5 6class Product extends Model implements HasFilesContract 7{ 8 use HasFiles; 9 10 protected $fillable = ['name', 'cover', 'gallery'];11 12 public function fileables(): array13 {14 return [15 File::make('cover')16 ->images()17 ->thumbnail(width: 400)18 ->fallback('/images/no-cover.png'),19 20 File::make('gallery')21 ->images()22 ->multiple()23 ->maxFiles(20)24 ->resize(maxWidth: 1920)25 ->convert('webp')26 ->compress(80)27 ->thumbnail(width: 400),28 ];29 }30}1public function rules(): array2{3 return [4 'name' => ['required', 'string', 'max:255'],5 'cover' => ['nullable', 'image', 'max:5120'],6 'gallery' => ['nullable', 'array', 'max:20'],7 'gallery.*' => ['image', 'max:5120'],8 ];9}1public function store(StoreProductRequest $request)2{3 $product = Product::create($request->validated());4 5 return redirect()->route('products.show', $product);6}#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.
1use Pharaonic\Laravel\Files\Definitions\File; 2 3public function fileables(): array 4{ 5 return [ 6 File::make('cover') 7 ->images() 8 ->disk('s3') 9 ->path('products/covers')10 ->visibility('public'),11 12 File::make('invoices')13 ->documents()14 ->multiple()15 ->disk('local')16 ->path('invoices'),17 ];18}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:
1File::make('invoices')2 ->documents()3 ->multiple()4 ->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.
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:
1use Pharaonic\Laravel\Files\Definitions\File;2use 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.
1use Pharaonic\Laravel\Uploader\Facades\Uploader;2 3$upload = Uploader::upload($request->file('cover'), [4 'disk' => 's3',5 'path' => 'campaigns/2026',6]);7 8$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.
1public function toArray($request) 2{ 3 return [ 4 'id' => $this->id, 5 'name' => $this->name, 6 'cover' => $this->file('cover')->url, 7 'gallery' => $this->file('gallery') 8 ->active() 9 ->get()10 ->map(fn ($image) => [11 'url' => $image->url,12 'thumbnail' => $image->thumbnail,13 'alt' => $image->meta->alt ?? null,14 ]),15 ];16} 1public function toArray($request) 2{ 3 return [ 4 'id' => $this->id, 5 'name' => $this->name, 6 'gallery' => $this->file('gallery') 7 ->get() 8 ->map(fn ($image) => [ 9 'id' => $image->id,10 'position' => $image->position,11 'is_active' => $image->is_active,12 'url' => $image->url,13 'meta' => $image->meta,14 'size' => $image->size,15 'status' => $image->upload->status ?? null,16 ]),17 ];18}Load the files once for a list:
1$products = Product::query()2 ->with('files')3 ->paginate();4 5return 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:
1public function reorder(Request $request, Product $product) 2{ 3 $request->validate([ 4 'order' => ['required', 'array'], 5 'order.*' => ['integer'], 6 ]); 7 8 $product->file('gallery')->reorder($request->input('order')); 9 10 return response()->noContent();11}12 13public function toggle(Product $product, int $file)14{15 $product->file('gallery')16 ->findOrFail($file)17 ->toggle();18 19 return back();20}The primary image is the first active one:
1$primary = $product->file('gallery')2 ->active()3 ->first();#5. A media list with images, videos and PDFs
1public function fileables(): array 2{ 3 return [ 4 File::make('media') 5 ->multiple() 6 ->maxFiles(15) 7 ->mixed() 8 ->images(fn (Image $images) => $images 9 ->maxFiles(10)10 ->thumbnail())11 ->videos(fn (Video $videos) => $videos12 ->maxFiles(3)13 ->thumbnail(at: 2)14 ->compress(crf: 26))15 ->documents(fn (Document $documents) => $documents16 ->accepts('application/pdf')),17 ];18}1@foreach ($lesson->file('media')->active() as $item)2 @if ($item->type === 'image')3 <img src="{{ $item->url }}" alt="{{ $item->meta->alt ?? '' }}">4 @elseif ($item->type === 'video')5 <video src="{{ $item->url }}" poster="{{ $item->thumbnail }}" controls></video>6 @else7 <a href="{{ $item->url }}">{{ $item->meta->title ?? 'Download' }}</a>8 @endif9@endforeachThe videos play their original until the queue finishes processing them.
#6. Picking an upload from a media library
1public function update(Request $request, Product $product) 2{ 3 $upload = Upload::query() 4 ->findOrFail($request->input('upload_id')); 5 $this->authorize('use', $upload); 6 7 $product->file('cover')->set($upload); 8 $product->file('cover')->setMeta(['alt' => $request->input('alt')]); 9 10 return back();11}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.
Contributors
Amazing people who made this package possible
This package wouldn't exist without the contributions of our amazing community. A huge thank you to everyone who has helped improve Laravel Has Files!
Want to Contribute?
We welcome contributions from everyone! Whether it's bug fixes, new features, or documentation improvements - every contribution counts.
Was this page helpful?
Thanks, that helps us decide what to improve.
Something wrong or missing? Report it on GitHub .