File Uploads and Storage System
Existing-resource snippets below assume the caller has authorized the project/resource and supplied $authorizedPostId. Configuration and relationship fragments belong inside their owning models; they are not replacement definitions for built-in models.
Manage project assets in the dashboard
Project assets are reusable files owned by a project. They are separate from attendee uploads, collection-entry assets and a plugin version's packaged files. Choose the correct owner before uploading; a project asset does not automatically become a published plugin asset.
- On the dashboard host, open
/p/{team}/{project}/assetsusing the intended team/project slugs. The list shows ID, name, MIME type and file size, with filename search and selection controls. - Use the page's asset uploader to choose the intended files. The UI accepts a broad file selection, while the server validates the actual upload contract. For large/direct uploads, record creation, byte transfer and completion/processing are separate stages described below.
- Reload the list and verify the saved file, original name/type/size and intended project. Select it through the consuming form/App/theme configuration's supported asset selector; an upload alone does not bind the file to that resource.
- Verify access and rendering as the intended consumer, including expired URLs, missing files and private data. Obtain a fresh authorized URL instead of embedding a temporary signed URL as a permanent asset identifier.
The permission catalog maps view_project_assets to reading and manage_project_assets to mutations. The reviewed controller explicitly authorizes individual/bulk download and deletion, but its list/store methods do not themselves call the same inline policy check, and the store request's authorize() returns true. Do not treat a catalog entry or a hidden upload button as proof that every transport enforces that permission; check route/middleware and denied direct requests in the target deployment. Project scoping and asset policy are separate checks.
Download selected project assets
Download Selected starts separate browser downloads, not a ZIP archive. The current UI limits a selection to 25 assets. The underlying bulk endpoint validates up to 100 supplied IDs, queries the current project's assets and returns files, missing and count; it does not send the file bytes in that JSON response. Each file result carries its ID, original filename and a temporary URL. missing reports matched records for which URL generation returned no URL, not every invalid or another-project ID supplied by a client. Compare the returned files with the intended selection.
The bulk controller requests 15-minute URLs; storage/signing configuration still governs their actual availability. The browser then starts individual downloads and can block repeated downloads until the user allows them. A success notification does not prove the browser saved every file. Single-asset download likewise returns JSON containing a URL, rather than streaming the original bytes from that controller. Keep the downloaded originals private when their contents require it.
Delete and verify project assets
Use the intended row or selected-assets delete control and inspect the confirmation's selected population. The bulk controller accepts up to 500 IDs, constrains its query to the project's assets and deletes individual model instances so lifecycle hooks run. Its reported deleted count is the matched/deleted model population, not a per-ID report for every submitted value. Another-project or missing IDs are not included by that scoped query.
Deletion can affect configurations that still reference the asset. Model deletion, pending storage cleanup, cached URLs and recovery of file bytes are separate effects; a successful redirect does not prove all physical objects have been purged or retained for restore. See Attachment and deletion side effects before implementing custom cleanup. Record dependents and the actual backup/recovery mechanism before removing files needed by a live experience.
Project-asset acceptance
With controlled files, verify ordinary upload and the configured large-upload path, actual content/metadata after reload, authorized selector resolution, allowed/denied operators, another project's ID, private serving behavior, expired/missing URLs, browser multi-download behavior and dependent-resource behavior after deletion. Inspect actual processing/cleanup status where those features are required. For failures, distinguish file validation, byte transfer, completion hook, queue processing, URL signing and the final consumer; the detailed troubleshooting section below covers those boundaries.
Overview
The GxP platform uses a flexible file upload and storage system built around the Uploadable trait. This system handles file uploads, storage, processing, and retrieval across different storage backends (local and cloud-based). It supports both small and large file uploads, automatic image variant generation, video transcoding, watermarking, and more.
Key Features:
- Multipart and direct-to-storage upload modes selected by the configured client contract; the default threshold is 20 MiB
- Automatic image variant generation with configurable dimensions
- Video transcoding with multiple quality levels (FHD, HD, SD)
- Video sprite generation for timeline previews
- Video transcription using Google Cloud Video Intelligence
- Image watermark overlays; media job configuration has separate limitations
- Multiple storage backends (local filesystem, Google Cloud Storage)
- Signed URL generation for secure file access
- Pending file-cleanup scheduling on model deletion
Architecture & Core Concepts
The Uploadable Trait
The Uploadable trait (app/Traits/Uploadable.php) is the heart of the upload system. When added to a model, it provides:
- Lifecycle Hooks: Automatically handles file uploads during model creation/update
- File Management: Stores/retrieves files and schedules deletion cleanup
- Processing Pipeline: Triggers jobs for image/video processing
- URL Generation: Creates signed URLs for secure file access
- Metadata Tracking: Stores file information (name, size, MIME type, etc.)
File Storage Structure
The default object-key layout is illustrated below, relative to the configured disk root/prefix. There is no universal extra uploads/ segment in the model key. The storage folder need not be the PHP model class, and schema-aware models can use a different path template:
{disk_root_or_prefix}/
└── {storage_folder}/
└── {model_id}/
└── {column_name}/
├── {filename}.ext # Original file
├── {filename}_thumbnail.ext # Image variant
├── {filename}_medium.ext # Image variant
├── {filename}_large.ext # Image variant
└── transcoded/ # Video processing
├── video-fhd.mp4
├── video-hd.mp4
├── video-sd.mp4
├── manifest.m3u8
├── large-sprite-sheet0000000000.jpeg
└── transcription/
└── transcription.json
Path templates and schema versions
uploadablePathTemplate($column) uses the model's persisted uploadable_schema when it names an entry in $uploadableSchema. For an unsaved model with schema zero, it first looks up the selected column's schema configuration. Otherwise it falls back to :storageFolder/:idColumn/:storageColumn. New schema-aware records receive their configured schema before persistence; changing configuration does not automatically migrate existing objects.
processPathTemplate($template, $fileDef) substitutes :storageFolder, :storageColumn and :idColumn from the resolved file definition/model. It also supports :model.attribute and :model['relation'].attribute. Missing model or related attributes become empty strings; an absent idColumn definition leaves that token unresolved. Ensure the required identifiers and relationships exist before constructing a path. Do not build storage keys in a client by copying the legacy diagram: obtain the model's resolved path or authorized URL instead.
Storage Environments
The system operates in two primary environments:
Local Environment
- Storage Disk:
local(Laravel's local filesystem driver) - Root:
storage/app/public; append the resolved model key, such asassets/{id}/file_name/{filename} - URLs: Standard Laravel public URLs (no signing required)
- Use Case: Development and testing
Cloud Environment (Production)
- Storage Disk:
gcs(Google Cloud Storage) - Path: configured bucket/prefix plus the resolved model key; do not hard-code
uploads/ - URLs: Signed temporary URLs with configurable expiry
- CDN Support: Optional CDN signing for improved performance
- Use Case: Production deployments
Configured disk behavior (config/filesystems.php):
| Disk | Current configuration and intended boundary |
|---|---|
local | Local driver rooted at storage/app/public, with the /storage URL. Do not assume this is private storage. |
gcs | Configured bucket and upload prefix, ASSET_DEFAULT_VISIBILITY defaulting to private; uses DOMAIN_API as the storage API URI outside the local environment. |
gcs_public | GCS under the configured prefix plus /public_assets, public visibility and one-day public cache metadata. Use only for intentionally public objects. |
public_upload | Local public storage when FILESYSTEM_DISK=local; otherwise the public GCS assets configuration. |
direct | GCS using the configured bucket/prefix and visibility, without the app storage API URI. Used for direct provider URLs; it is not the browser upload mode switch. |
The cloud definitions accept GOOGLE_CLOUD_KEY_FILE or decoded GOOGLE_CLOUD_KEY, project ID, bucket and prefix. Use the existing environment configuration and credential provisioning; these definitions are not a reason to expose service-account credentials to a browser. Bucket/IAM and the serving path must enforce the intended access policy independently of the disk name.
Read URLs, expiry and access boundaries
Authorize access to the owning project/resource before returning a file URL. The URL helpers generate locators or storage credentials; they do not perform the caller's project permission check.
| Helper | Current behavior |
|---|---|
url($column) | Returns an ordinary URL after a cached file-existence check; uses domain-aware routing when configured |
signedUrl($column, $expiry = 5) | Uses minutes. Local disks and adapters without temporary-URL support fall back to an ordinary URL; otherwise it requests temporary/domain-aware or configured CDN-prefix signing |
directSignedUrl($column, $expiry = 5) | Uses minutes and the direct disk regardless of the file's named disk; this method does not first call fileExists |
signedUrlWithPrefix($column, $expiry = 3600) | Also uses minutes: its standalone default is 3,600 minutes (60 hours), not 3,600 seconds. Pass an explicit lifetime when using this method directly |
Use a private storage configuration and verify the actual returned URL and serving policy. A method name containing “signed” is not evidence that every branch enforces expiry or attendee authorization. Do not expose a public/local fallback for content that must remain private.
When app URLs are enabled, DomainAwareStorageService substitutes its current configured domain while retaining the path/query. That substitution is a URL-generation operation, not proof that the destination host is configured to validate and serve that signature. Test the complete deployment path, including certificate, signature, expiry and resource access.
Generate temporary links close to use and handle expiry by obtaining a fresh authorized URL. Keep signed URLs out of logs and persistent client configuration. If caching them, scope the cache to the authorized resource and serving domain, invalidate on file changes, and expire it before the URL with a safety margin. A shared asset_id-only URL cache is insufficient for differing domain/access contexts.
File Upload Flow
Multipart upload flow
This is the traditional multipart form upload:
1. User selects file(s) in frontend
2. Frontend sends multipart/form-data POST request
3. Laravel receives UploadedFile instances
4. Model's 'creating' event fires
├─ File is temporarily stored in temp/{column}/{uuid}/
└─ File metadata is JSON-encoded and stored in model column
5. Model is saved to database
6. Model's 'created' event fires
├─ File is moved from temp/ to final location
├─ processFileUpload() is called
└─ Processing jobs are dispatched
7. Background jobs process file
├─ CreateImageVariant jobs (for images)
├─ CreateMediaTranscoding job (for videos)
└─ ExtractUploadDetailsJob (for metadata)
8. Processing flag updated on completion
The current project-asset controller reads validated asset items and optional matching asset_name entries. For ordinary AJAX uploads it returns an array of created asset records. Send X-Requested-With: XMLHttpRequest when using this dashboard contract; a normal navigation submission redirects to the project asset list. Server permission and file validation still apply.
Large File Upload Flow
The asset dropzone uses direct storage upload when any selected file exceeds the boot-configured threshold or the total selection exceeds it. The fallback threshold is 20 * 1024 * 1024 bytes (20 MiB); this is a mode-selection threshold, not a universal server maximum. A file exactly at the threshold does not exceed it.
- Submit metadata placeholders under the asset field, normally
asset; do not send the oldasset_metadata/use_large_uploadcontract. - The controller validates the placeholders, creates project asset records and returns
assetsplusuploadUrlsfor AJAX requests when direct-upload URLs are available. - Match each file to
uploadUrls[filename]and PUT its bytes to that URL using the required content type. - Confirm storage finalization and subsequent processing separately. Completing the PUT does not prove variants, transcoding or transcription are ready.
Example request body for the project asset endpoint:
{
"asset": [
{
"filename": "docs-demo-video.mp4",
"size": 52428800,
"type": "video/mp4",
"lastModified": 1700000000000,
"large_upload": true
}
],
"asset_name": ["docs-demo-video.mp4"]
}
Use the owning project's authorized dashboard upload route and JSON/AJAX headers. asset_name is optional, but when supplied its count must match the asset count. An optional parent_asset_id must belong to that project. The server applies its SafeUploadable rules; client MIME metadata and the size threshold do not replace server validation or storage limits.
Finalization is a separate stage
For the generic uploadable-model branch, the storage-finalization callback resolves the object key through UploadableRegistry to an owning model, ID and uploadable column. Status-less paths are ignored for this large-upload flow, preventing generated variants from recursively starting processing. A matched row must still be waiting_for_upload before processing starts; an already transitioned row is acknowledged without restarting it.
The callback can return 200 for a key outside its processing pattern, and its “processed successfully” message means the processing entry point returned—it does not await every queued job. Social-post and AI-message response paths have additional specialized handling; do not infer that every callback uses this generic branch. A missing matched model returns 404; a thrown processing error sets the configured status to failed and returns 500. Use the provisioned storage callback and incoming webhook authentication (repository reference: /webhooks/incoming); a browser PUT completion is not a substitute for authenticated finalization.
Shared form helper versus asset dropzone
resources/js/Composables/useLargeFileUploads.js supports top-level form fields containing a File, FileList or array of Files. It mutates qualifying values into placeholders and returns the original files in a map keyed by filename. It checks the first file of a FileList/array and replaces the entire field; it does not recursively walk nested forms, preserve every file in a multi-file field, or choose direct mode based on the aggregate size. Those behaviors differ from the asset dropzone's selection-wide logic.
performLargeUploads uses fetch PUT with Content-Type: application/octet-stream and rejects a non-OK response. It silently skips files without a matching signed URL and provides no progress events or automatic retries. Validate that every intended file has a URL before treating a resolved promise as success. Duplicate filenames collide in the map; do not use that helper as a lossless multi-file transport without addressing filename uniqueness.
The asset dropzone has its own XMLHttpRequest progress/retry UI and records a missing URL as a per-file error. Its success UI reports transfer results; verify the asset's final processing state before displaying processed variants or video output. Keep signed URLs out of logs and reuse them only according to their lifetime/required headers. The trait can sign an upload using the file's MIME content type, while the shared helper always sends application/octet-stream; mocked helper tests do not prove those values agree with the storage signature. Verify the actual signed-header contract and browser/storage behavior for the owning endpoint.
Configuration Options
Global Configuration
File Size Limits (config/filesystems.php):
// Threshold for switching to large upload mode
'large_upload_threshold' => env('LARGE_UPLOAD_THRESHOLD', 20 * 1024 * 1024), // 20MB
// Maximum file size allowed for large uploads
'max_large_upload_file_size' => env('MAX_LARGE_UPLOAD_FILE_SIZE', 1024 * 1024 * 1024 * 10), // 10GB
CDN Signing (illustrative configuration without fallback credentials; provision deployment-specific values rather than relying on source defaults):
'use_app_urls' => env('USE_APP_URLS', false),
'cdn_signing_key' => env('CDN_SIGNING_KEY'), // Provision the deployment's signing key
'cdn_signing_key_name' => env('CDN_SIGNING_KEY_NAME'), // Matching provisioned key name
Environment Variables
Add to your .env file:
# Storage Configuration
FILESYSTEM_DISK=gcs # 'local' for dev, 'gcs' for production
ASSET_DEFAULT_VISIBILITY=private # 'public' or 'private'
# Google Cloud Storage (Production)
GOOGLE_CLOUD_PROJECT_ID=your-project-id
GOOGLE_CLOUD_STORAGE_BUCKET=your-bucket-name
GOOGLE_CLOUD_STORAGE_PATH_PREFIX=uploads
GOOGLE_CLOUD_KEY=base64_encoded_service_account_json
# Upload Limits
LARGE_UPLOAD_THRESHOLD=20971520 # 20MB in bytes
MAX_LARGE_UPLOAD_FILE_SIZE=10737418240 # 10GB in bytes
# CDN Signing (Optional)
USE_APP_URLS=true
CDN_SIGNING_KEY=your-signing-key
CDN_SIGNING_KEY_NAME=your-key-name
Setting Up Models for File Uploads
Basic Setup
The following is an illustrative custom model and migration, not a replacement for the built-in ProjectAsset. The built-in model also has project relationships, an observer, quota/tag behavior, appended URL data and thumbnail/medium variants. Preserve those integrations when extending it.
To enable file uploads on a new model:
Step 1: Add the Uploadable trait
<?php
namespace App\Models;
use App\Traits\Uploadable;
use Illuminate\Database\Eloquent\Model;
class DocumentationAsset extends Model
{
use Uploadable;
protected $fillable = ['project_id', 'name', 'slug', 'file_name', 'upload_status'];
// Define uploadable configuration
protected $uploadableFileList = [
[
'class' => 'assets', // Storage folder name
'column' => 'file_name', // Database column name
'rename' => true, // Auto-rename files
'status' => 'upload_status', // Column for upload status tracking
],
];
}
Step 2: Create database migration
Schema::create('documentation_assets', function (Blueprint $table) {
$table->id();
$table->foreignId('project_id')->constrained();
$table->string('name');
$table->string('slug');
// File metadata stored as JSON
$table->json('file_name')->nullable();
// Upload status: 'waiting_for_upload', 'processing', 'processed'
$table->string('upload_status')->default('processed');
$table->timestamps();
});
Step 3: Validate the owning endpoint's file contract
The current StoreProjectAssetRequest uses asset as a required nonempty array. Each item passes SafeUploadable, which accepts either an actual UploadedFile or a large_upload metadata object. Actual files have the per-slot multipart size cap; metadata requires a safe filename, a positive numeric size and compliance with the configured global direct-upload hard cap. Client metadata is not proof of stored bytes or MIME safety.
Optional asset_name entries are strings up to 255 characters and must match the asset count when supplied. An optional parent_asset_id must resolve within the route's project. Reuse the owning endpoint's current validation and authorization; do not create a parallel request class using legacy metadata fields.
Step 4: Make direct-upload finalization discoverable
The minimal model above is exercised for multipart storage; a new model does not become a complete direct-upload feature merely by adding the trait. UploadableRegistry::build() scans PHP files under app/Models, resolves their App\Models\... classes, checks recursive trait use and collects uploadablePathPatterns(). A model outside that discovery location needs an explicit supported integration rather than an assumption that the webhook will find it.
Each configured column contributes its current configured schema template, or the default :storageFolder/:idColumn/:storageColumn. The compiler captures :idColumn as the model lookup ID, substitutes the configured folder/column literally and treats model/relation attribute tokens as single path-segment wildcards. Patterns can match after a prefix boundary and tolerate a trailing filename; they are sorted by literal specificity. Verify that a representative finalized object key resolves to the intended model, ID, column and status field. Overlapping templates or older persisted schema paths require explicit checks; discovery is not a blanket guarantee that every historical layout matches.
The registry first uses its process memo, then bootstrap/cache/uploadable-patterns.php when present, otherwise a fresh scan. The platform's uploadable:cache and uploadable:clear command implementations manage the compiled file and the invoking process's memo. Coordinate cache generation/invalidation and long-running process refresh through the private deployment runbook after model/schema changes; clearing one process's memo does not refresh every running worker.
The authenticated finalization handler additionally requires a configured status column, a found model and waiting_for_upload before starting that model's processing path. A model with no status mapping is skipped; an already-transitioned model can receive an acknowledgment without new work. Validate the whole metadata → object PUT → authenticated callback → processing/output chain for the intended feature. The local multipart fixture does not prove this provider/webhook path.
Uploadable Configuration Properties
The $uploadableFileList array accepts the following configuration options:
| Property | Type | Required | Default | Description |
|---|---|---|---|---|
class | string | No | Model class name | Storage folder name (e.g., 'assets', 'social-posts') |
column | string | Yes | - | Database column name where file metadata is stored |
disk | string | No | config('filesystems.default') | Storage disk to use ('local', 'gcs', etc.) |
rename | boolean | No | false | Build a name from six random characters plus a timestamp and the extension; otherwise use the supplied/original basename, with length truncation |
status | string | No | false in resolved definition | Column name for tracking upload/processing status |
idColumn | string | No | 'id' | Primary key column name (use if different from 'id') |
variants | array | No | null | Image variant configurations (see Image Variants section) |
video | array | No | false | Video processing options (see Video Processing section) |
audio | array | No | false | Audio processing options; transcode and transcription are handled by the media job |
schema | integer | No | 0 | New-record path schema selector; requires a matching model $uploadableSchema entry |
watermarks | array | No | null | Watermark configurations (see Watermarking section) |
enabled | string | No | null | Boolean column name to conditionally enable/disable upload |
Multiple File Uploads
A model can have multiple uploadable columns:
protected $uploadableFileList = [
[
'class' => 'plugin-version',
'column' => 'file_name', // JavaScript bundle
'rename' => true,
],
[
'class' => 'plugin-version',
'column' => 'style_file_name', // CSS file
'rename' => true,
],
];
Image Variants & Watermarking
Image Variant Generation
The Uploadable trait can automatically generate multiple variants of uploaded images in different sizes:
protected $uploadableFileList = [
[
'class' => 'social-posts',
'column' => 'file_path',
'status' => 'upload_status',
'rename' => true,
'variants' => [
'thumbnail' => [128, 128], // Named variant with dimensions
'medium' => [512, 512],
'large' => [2048, 2048],
],
],
];
Variant configuration:
- Named entries such as
'thumbnail' => [128, 128]supply dimensions. - List entries such as
['thumbnail', 'medium', 'large']use built-in job defaults: 64×64, 512×512 and 1024×1024 respectively. - A custom named variant needs valid dimensions or a supported default-name mapping. An unknown name alone does not define a resize operation.
remove_bgis a separate conditional background-removal path, not an ordinary resize dimension name.
Processing Details:
- Variants are created using ImageMagick via the
CreateImageVariantjob - The job calls
cropThumbnailImage(). For the variant named exactlythumbnail, the configured width and height are the crop target. - For other variants, it computes width from the source aspect ratio and configured height. The configured width is not a maximum bound. For example, an 80×20 source with a non-thumbnail
[10, 8]variant produces 32×8, not a result bounded by 10×8. - The current path can upscale; do not assume a no-enlargement policy.
- Original file is preserved
Accessing Variants:
$post = SocialStreamPost::findOrFail($authorizedPostId);
// Original file
$originalUrl = $post->signedUrl('file_path');
// Variants (auto-appended to model)
$thumbnailUrl = $post->signedUrl('file_path_thumbnail');
$mediumUrl = $post->signedUrl('file_path_medium');
$largeUrl = $post->signedUrl('file_path_large');
// Check variant properties
$thumbnailPath = $post->file_path_thumbnail_path;
$thumbnailMime = $post->file_path_thumbnail_mime;
$thumbnailName = $post->file_path_thumbnail_name;
Watermarking
Image variants support watermark overlays. The current video transcoder accepts a watermark argument, but its overlay configuration is commented out; passing the same configuration does not apply a video watermark. The system supports dynamic watermarks loaded from related models:
protected $uploadableFileList = [
[
'class' => 'social-posts',
'column' => 'file_path',
'variants' => [
'medium' => [512, 512],
'large' => [2048, 2048],
],
'watermarks' => [
[
'relations' => 'socialStream.asset', // Navigate through relationships
'file_column' => 'file_name', // Column on related model
'settingsRelation' => 'socialStream', // Relation for settings
'opacity_column' => 'watermark_opacity', // Opacity value (0-1)
'enable_column' => 'watermark_enabled', // Boolean to enable/disable
],
],
],
];
Watermark Configuration:
| Property | Type | Required | Description |
|---|---|---|---|
relations | string | Yes | Dot-notation path to related model with watermark file (e.g., 'socialStream.asset') |
file_column | string | Yes | Column name on the related model containing the watermark file |
settingsRelation | string | No | Alternative relation path for settings columns |
opacity_column | string | No | Column name for opacity value (0.0 to 1.0, default: 0.45) |
enable_column | string | No | Boolean column to enable/disable watermarking |
The resolver uses the first viable watermark definition, not every entry in the list. It traverses relationships with first(), skips missing related models or missing paths and reads opacity from the configured settings model (or the watermark model). The enable flag is checked on the settingsRelation path when that path is configured; do not assume an enable_column without that settings path is enforced identically.
The image job reads the watermark path from the same disk as the uploaded source. A related model on another disk does not automatically make its file available there. PNG/SVG/JPG decoding depends on the installed ImageMagick delegates and policy; validate the formats used by the deployment.
How image watermarking works:
- System traverses relationships to find watermark file
- Watermark image is loaded from the source disk with ImageMagick
- Watermark is resized for the generated image dimensions
- The resized watermark is applied through the image texture/composite path
- Applied with specified opacity using ImageMagick's
COMPOSITE_DISSOLVE - For images: Creates both regular variant and
_overlayvariant - The current video job does not apply its passed watermark configuration; image overlays do not establish video overlay support
Overlay Variants:
When watermarking is enabled for images, two versions are created:
file_path_medium: Variant without watermarkfile_path_medium_overlay: Variant with watermark applied
// Access watermarked version
$watermarkedUrl = $post->signedUrl('file_path_large_overlay');
Watermark Example:
// Model: SocialStreamPost
// Relationships: post->socialStream->asset (watermark file)
// post->socialStream (watermark settings)
// Existing relationship fragment in SocialStream; preserve the full model.
public function asset()
{
return $this->belongsTo(\App\Models\ProjectAsset::class, 'project_asset_id');
}
// When a post is uploaded:
// 1. Check if $post->socialStream->watermark_enabled === true
// 2. Load watermark from $post->socialStream->asset->file_name
// 3. Get opacity from $post->socialStream->watermark_opacity
// 4. Apply to configured image variants; do not assume video overlay support
Video Processing Features
The Uploadable trait supports comprehensive video processing through three main processors:
Available Processors
protected $uploadableFileList = [
[
'class' => 'social-posts',
'column' => 'file_path',
'status' => 'upload_status',
'video' => [
'transcode', // Multi-bitrate transcoding
'sprite', // Timeline preview sprites
'transcription', // Speech-to-text transcription
],
'watermarks' => [
// A passed video watermark is not currently applied by the transcoder
],
],
];
1. Transcode Processor
Submits Google Cloud Transcoder job configurations for multiple video streams and an HLS manifest. Output labels are source-relative, not fixed resolution promises:
Generated Files:
transcoded/video-fhd.mp4— source dimensions rounded down to even valuestranscoded/video-hd.mp4— two-thirds source dimensions, rounded down to even valuestranscoded/video-sd.mp4— half source dimensions, rounded down to even valuestranscoded/manifest.m3u8- HLS manifest for adaptive streaming
Accessing Transcoded Videos:
$post = SocialStreamPost::findOrFail($authorizedPostId);
// Original video
$originalUrl = $post->signedUrl('file_path');
// Transcoded versions
$fhdUrl = $post->signedUrl('file_path_fhd');
$hdUrl = $post->signedUrl('file_path_hd');
$sdUrl = $post->signedUrl('file_path_sd');
// HLS manifest (requires special signing)
$manifestUrl = $post->signedUrlWithPrefix('file_path_manifest', 5);
// Video metadata (extracted during processing)
$duration = $post->duration('file_path'); // In seconds
$resolution = $post->resolution('file_path'); // e.g., "1920x1080"
2. Sprite Processor
Generates sprite sheets for video timeline previews:
Generated Files:
transcoded/large-sprite-sheet0000000000.jpeg- Large preview spritestranscoded/small-sprite-sheet0000000000.jpeg- Small preview spritestranscoded/video-hd.mp4- HD version used for sprite generation
Accessing Sprites:
$largeSpriteUrl = $post->signedUrl('file_path_large_sprite');
$smallSpriteUrl = $post->signedUrl('file_path_small_sprite');
3. Transcription Processor
Submits a speech-transcription request to Google Cloud Video Intelligence. The current service selects en-US with automatic punctuation; this path does not infer a language from the portal locale:
Generated Files:
transcription/transcription.json- Full transcription response from Google Cloud- Auto-generated WebVTT subtitle file (created on-the-fly)
Accessing Transcription:
$post = SocialStreamPost::findOrFail($authorizedPostId);
// Check if transcription exists
if ($post->metadata && isset($post->metadata['transcription'])) {
// Raw transcription data
$transcription = $post->metadata['transcription'];
// Generate VTT subtitles
$vttContent = $post->generateVttFromTranscription($transcription);
// Access transcription file URL
$transcriptionUrl = $post->signedUrl('file_path_transcription');
}
VTT Format Example:
WEBVTT
00:00:00.000 --> 00:00:02.500
Hello and welcome to
00:00:02.500 --> 00:00:05.000
this video demonstration of
Audio processing
The upload configuration can also supply an audio processor list. CreateMediaTranscoding uses extracted hasVideo metadata to select the video or audio path and clears flags belonging to the unused path. It does not choose solely from the filename. Metadata extraction failure is logged and the job can continue; missing hasVideo falls back to the audio path.
The current audio transcode configuration outputs transcoded/audio-sd.mp3 using MP3, 128,000 bits/second, two channels and 48,000 Hz. Transcription is selected from the active video/audio processor list. Validate the actual produced stream and playback behavior; successful job construction does not prove a provider accepts every input.
Processing flow
- Storage finalization or the ordinary upload lifecycle invokes
processFileUpload. - With configured media processors, it queues
CreateMediaTranscoding, which calls metadata extraction throughTranscoderServicedirectly. This is not a separateExtractUploadDetailsJobrunning ahead of it. - FFprobe reads metadata through a temporary direct-storage URL. Google Cloud Transcoder handles configured transcoding/sprite jobs; Video Intelligence handles configured speech transcription.
- Submission returns before the provider finishes. Transcription initially writes under the job's
model_response/transcription/output; the supported callback/response-job path moves and applies the result to the owning model. - Inspect the provider outcome, authenticated callback, persisted metadata/flags and required files as separate stages. The transcoding-status callback can acknowledge after a lookup/processing exception; HTTP 200 alone does not establish a successful transcode.
Without configured video/audio processors, the trait queues ExtractUploadDetailsJob and clears its processing flag independently. That job logs extraction exceptions without rethrowing them, so a cleared flag or completed queue job is not proof that metadata was extracted.
Processing Status Tracking
The system tracks processing status in the model's metadata:
$post = SocialStreamPost::findOrFail($authorizedPostId);
// Check overall status
$isProcessing = $post->upload_status === 'processing';
// Check individual processor status
$metadata = $post->metadata;
$processingStatus = $metadata['processing_status'] ?? [];
// Example:
// [
// 'transcode' => 1, // Still processing
// 'sprite' => 0, // Cleared; verify outcome
// 'transcription' => 1 // Still processing
// ]
Video Processing Jobs
CreateMediaTranscoding (app/Jobs/CreateMediaTranscoding.php):
- Timeout: 600 seconds (10 minutes)
- Handles transcoding, sprite generation, and transcription
- Uses
TranscoderServicefor FFprobe metadata and Google Cloud Transcoder submission - Uses
VideoIntelligenceServicefor transcription
ExtractUploadDetailsJob (app/Jobs/ExtractUploadDetailsJob.php):
- Extracts metadata (duration, resolution, codec) using FFprobe
- Updates model with extracted information
- Runs when no video/audio processors are configured; it is not a completion barrier
Video processor configuration fragment
Add this fragment to an existing authorized model using Uploadable; it is not a complete model or migration. Supply the video_file metadata column, upload_status column, project/ownership relationships and the discovery/finalization prerequisites above. For per-processor flags, provide an initialized non-null metadata array and its array cast; a nullable column with only a cast does not establish that initial state.
protected $casts = [
'metadata' => 'array', // Merge with the owning model's other casts.
];
protected $uploadableFileList = [
[
'class' => 'video-posts',
'column' => 'video_file',
'status' => 'upload_status',
'rename' => true,
'video' => ['transcode', 'sprite', 'transcription'],
],
];
Configure and verify the disk, queue, FFprobe, provider services and authenticated result callbacks in the owning environment before expecting media outputs. Video watermark overlays are not implemented by the current transcoder. The older sample's organization.branding/organization.settings relationships were illustrative and undefined; do not copy them into a model without real relationships. If image watermarking is required, use the separately documented image configuration and verify its source disk and resolved asset.
Events & Customization
The Uploadable trait fires events at various stages of the upload and processing lifecycle. Models can customize these events to trigger additional logic.
Default Events
Built-in Eloquent Events (handled automatically by Uploadable):
creating: Stores file temporarilycreated: Moves file to final location, starts processingupdating: Handles file replacementupdated: Processes updated filedeleting: Creates pending file-deletion records and invalidates existence cache; storage cleanup is separate from deleting the database rowretrieved: Sets up file URLs and metadata
Custom Upload Events
Models using Uploadable can define lifecycle events. Event names do not prove that every asynchronous output succeeded; inspect the emitting method and processing/artifact outcomes before using an event to publish content.
1. Image Variant Completed Event
The configured variant event can fire when processingFlag(..., 0) is called. That call is not restricted to successful generation of every requested variant.
Default: No event fired (returns null)
Customization:
// Existing method fragment from SocialStreamPost; preserve its full model.
protected function getImageVariantCompletedEvent(): string
{
return \App\Events\SocialStreamPostVariantCompleted::class;
}
When It Fires:
processingFlag(..., 0)can emit the configured variant event, including when other processor flags remain set.- The image batch uses
allowFailures()and clears variant flags infinally; a cleared flag does not establish a successful output. - Some no-work paths also invoke completion handling. Verify the actual artifact and failure outcome rather than inferring success from the event name.
The existing SocialStreamPostVariantCompleted and SocialStreamPostUploadCompleted events expose the post as $event->model (and through getModel()), not $event->post. They participate in platform workflow/event behavior; do not replace their implementation with a simplified application-local event class.
Listener example: reconcile before acting:
public function handle(SocialStreamPostVariantCompleted $event): void
{
$post = $event->model->fresh();
if (! $post) {
return;
}
// Inspect required output files, processing failures and publication policy
// before sending a completion notification or publishing the post.
\Log::info('Upload processing signal received', [
'post_id' => $post->id,
'upload_status' => $post->upload_status,
]);
}
2. Upload Completed Event
processAllFiles() invokes processing for each configured column and then emits this configured event. It does not await queued variant/media jobs, so the event is not a barrier proving all outputs are ready.
Default: No event fired (returns null)
Customization:
// Existing method fragment from SocialStreamPost; preserve its full model.
protected function getUploadCompletedEvent(): string
{
return \App\Events\SocialStreamPostUploadCompleted::class;
}
When It Fires:
- After
processAllFiles()completes - Can be manually triggered by calling
$model->processAllFiles()
Use Case:
// Start processing; do not interpret this as asynchronous completion
$post = SocialStreamPost::findOrFail($authorizedPostId);
$post->processAllFiles(); // Starts each configured processing path and emits the configured event
Event Registration
The application disables automatic event discovery in EventServiceProvider::shouldDiscoverEvents(). Add an explicit mapping or use an existing subscriber; adding a class with a typed handle method alone does not register it. Preserve existing listener/subscriber registrations.
An actual mapping in app/Providers/EventServiceProvider.php is:
// Existing entry inside $listen; not a replacement provider definition.
\App\Events\AiSessionMessageUploadCompleted::class => [
\App\Listeners\AiSessionMessageUploadCompletedListener::class,
],
Custom event/listener names in model fragments must be implemented and registered for that model. Do not map an upload signal directly to publication without readiness and policy checks.
Processing Status Flags
The processingFlag() method manages upload processing status:
Usage:
$post = SocialStreamPost::findOrFail($authorizedPostId);
// Check if processing
$isProcessing = $post->upload_status === 'processing';
// Check specific processor status (for models with metadata)
$metadata = $post->metadata;
$processingStatus = $metadata['processing_status'] ?? [];
// Example status:
// [
// 'thumbnail' => 1, // Still processing
// 'medium' => 0, // Cleared; verify outcome
// 'large' => 1, // Still processing
// 'transcode' => 1, // Still processing
// ]
How It Works:
- Processor entries in
metadata->processing_statususe1for pending/active work and0for cleared work. - With a configured status column, the trait writes string values such as
processing/processed; these are separate from the numeric metadata entries. - Clearing one processor may emit a variant event while another remains active. Reload persisted state when evaluating readiness.
- Cleared flags can also result from an allow-failures batch finalizer. Inspect required storage artifacts and failure outcomes; zero is not a complete success certificate.
Custom Status Tracking:
// In your model
protected $uploadableFileList = [
[
'column' => 'file_path',
'status' => 'upload_status', // Column to track status
'variants' => ['thumbnail' => [128, 128]],
],
];
// Status values:
// - 'waiting_for_upload': Large upload, awaiting file
// - 'processing': File is being processed
// - 'processed': Processing flags cleared; verify required outputs/failures separately
Event-Driven Workflows
For automatic publication, handle the event as a signal to reconcile readiness. Reload the owning model, verify every required output exists, inspect failed/partial processing and apply the project's moderation/publication policy. Do not auto-approve a post solely because an upload event fired or a flag became zero. Queue expensive follow-up work with a deduplication key so repeated signals do not repeat the business action.
Existing AI-message reconciliation example (app/Listeners/AiSessionMessageUploadCompletedListener.php):
public function handle(\App\Events\AiSessionMessageUploadCompleted $event): void
{
$message = $event->model->fresh();
if (! $message instanceof \App\Models\AiSessionMessage) {
return;
}
$message->dispatchCompletedEventIfReady();
}
This invokes the AI-message model's readiness check and completion-dispatch claim before emitting its next event. The claim uses a finite-lived cache entry and allows dispatch if the cache claim throws; it is not a durable exactly-once guarantee. It is an existing model-specific integration, not a generic method available on every Uploadable model. Custom AI enrichment needs a configured supported AI integration, defined destination fields and its own failure/idempotency handling; there is no built-in AiVisionService::detectLabels()/generateCaption() API to copy from this guide.
Frontend Integration Patterns
Frontend mounting prerequisites
The dropzone example below mounts inside the existing platform Vue/Inertia application, with its HTTP, route, project/team and store integrations. Without createConfig.route, resolveUploadRoute uses the current page's project (or active project store) and currentTeam.slug to generate dashboard.project.assets.store. A detached page without that context cannot use the minimal example as-is. An explicit createConfig must identify a compatible authorized endpoint; changing a route prop does not implement direct-upload responses or processing callbacks for that endpoint.
The frontend uses a consistent pattern for file uploads across the application. Here are the key components and usage patterns:
Upload Component Types
1. AssetUploaderDropzone (Full-Featured Upload)
Used for bulk asset uploads with drag-and-drop, progress tracking, and large file support.
Location: resources/js/Components/AssetUploaderDropzone.vue
Features:
- Drag-and-drop file selection
- Multi-file upload support
- Automatic large file detection
- Individual file progress tracking
- Retry failed uploads
- File renaming before upload
Usage Example:
<template>
<AssetUploaderDropzone
:file-types="['.jpg', '.png', '.gif', '.mp4']"
@uploaded="handleUploadComplete"
/>
</template>
<script setup>
import AssetUploaderDropzone from '@/Components/AssetUploaderDropzone.vue'
const handleUploadComplete = (assets) => {
console.log('Uploaded assets:', assets)
// Refresh asset list or navigate to asset details
}
</script>
2. AssetPickerFile (Modal Upload + Selection)
Used within forms to select existing assets or upload new ones.
Location: resources/js/Components/Mod/v2/CardElements/File/AssetPickerFile.vue
Features:
- Modal interface for asset selection
- Upload new files from within modal
- Browse existing assets
- Filter by file type
- Preview images before selection
Normalized Mod v2 element fragment (insert through the owning graph/builder, with team/project route context):
// ShowV2.vue page definition
{
type: 'file',
style: 'asset-picker',
name: 'logo_file',
label: 'Company Logo',
displayType: 'thumbnail', // 'thumbnail' or 'input'
acceptedFileTypes: ['.png', '.jpg'], // File type filter
valuePrefix: 'asset_', // Optional ID prefix
searchRoute: {
route: 'dashboard.project.assets.index',
params: { project: projectSlug, team: teamSlug }
},
uploadRoute: {
route: 'dashboard.project.assets.store',
params: { project: projectSlug, team: teamSlug }
},
}
Frontend Store Integration
Asset Picker Store
Manages asset state, fetching, and uploads for the AssetPickerFile component.
Location: resources/js/Components/Mod/v2/Store/assetPickerStore.js
Key Methods:
import { useAssetPickerStore } from '@/Components/Mod/v2/Store/assetPickerStore'
const assetPickerStore = useAssetPickerStore()
// Configure routes
assetPickerStore.setSearchRoute({
route: 'dashboard.project.assets.index',
params: { project: 'my-project', team: 'my-team' }
})
assetPickerStore.setUploadRoute({
route: 'dashboard.project.assets.store',
params: { project: 'my-project', team: 'my-team' }
})
// Fetch assets
await assetPickerStore.fetchAssets()
// Upload new assets
// selectedFiles is an array of actual File instances from the user's selection.
const files = selectedFiles.map((file) => ({ file, name: file.name }))
await assetPickerStore.uploadAssets(files)
// Get asset by ID
const asset = assetPickerStore.getAssetById(123)
// Get asset URL
const url = assetPickerStore.getAssetUrl(123)
fetchAssets reuses a nonempty list for the same resolved route; its cache key does not include changed accepted-type/sort options. Use refreshAssets(identifier, listOptions) when those options change and fetchPage for subsequent pages. A caught list error returns an empty array, so an empty result alone does not establish an empty project.
uploadAssets sends multipart asset[]/asset_name[] and ingests an array response. It does not implement the direct signed-URL PUT protocol; an object response containing assets/uploadUrls is not ingested and can return an empty list after a success toast. Use the appropriate dropzone/direct-upload integration for that flow and inspect returned records/transfer outcomes.
The singleton store retains its ID cache when only its search route changes. Clear and reinitialize its routes/bindings when switching project/team context; cached URLs are not an authorization decision. clearStore() also resets configured routes, so set the new context before fetching again.
Asset Store (Legacy)
Simpler store for basic asset list management.
Location: resources/js/Store/assetStore.js
Key Methods:
import { useAssetStore } from '@/Store/assetStore'
const assetStore = useAssetStore()
// Copies project.assets already supplied to the page; this does not fetch a server list.
await assetStore.populateAssetList(project)
// Add new asset
assetStore.addAsset({
id: 456,
name: 'new-file.png',
asset_url: 'https://...'
})
// Access asset list
const assets = assetStore.assetList
Form Builder Integration
The renderer generation matters. Normalized Mod v2 elements use type: "file", style: "asset-picker" and a display type of thumbnail or input. The following is a legacy fields-list fragment using the supported dotted file type, not a complete v2 root/cards/elements graph. Use the builder appropriate to the owning schema:
Asset Picker Element:
// In your ShowV2 page configuration
{
title: "Media Settings",
tabId: "media",
cards: [{
type: "fields_list",
fieldsList: [
{
type: "file.asset-picker",
name: "header_image",
label: "Header Image",
displayType: "thumbnail",
acceptedFileTypes: [".jpg", ".png", ".webp"],
searchRoute: {
route: "dashboard.project.assets.index",
params: {
project: route().params.project,
team: route().params.team
}
},
uploadRoute: {
route: "dashboard.project.assets.store",
params: {
project: route().params.project,
team: route().params.team
}
},
},
{
type: "file.asset-picker",
name: "intro_video",
label: "Introduction Video",
displayType: "input",
acceptedFileTypes: [".mp4", ".webm"],
searchRoute: {
route: "dashboard.project.assets.index",
params: {
project: route().params.project,
team: route().params.team
}
},
uploadRoute: {
route: "dashboard.project.assets.store",
params: {
project: route().params.project,
team: route().params.team
}
},
}
]
}]
}
Direct Upload Pattern (Large Files)
Use the current direct-upload flow and distinguish the shared form helper from the asset dropzone. Validate complete file-to-URL correspondence, check each PUT response, and wait for the owning model's finalization/processing state. Do not infer a retry, finalization call or per-file progress API from performLargeUploads alone.
Troubleshooting & Best Practices
Common Issues
1. Upload Fails with "File too large"
Symptom: A multipart upload is rejected before or during request validation.
The mode-selection threshold is not the only limit: request rules, PHP/proxy body limits and storage policy can reject a request independently. Identify whether the response came from the application or an upstream server, then inspect the owning endpoint's validation error. Compare byte limits with validation rules expressed in KiB. The asset dropzone checks both individual and aggregate selection size; the shared form helper has a different contract. Switching to direct mode changes transport, not authorization or the permitted file types/maximum size.
2. Signed URLs Return 403 Forbidden
Symptom: Accessing file URLs results in 403 errors Cause: URL signature expired or CDN signing misconfigured Solutions:
- Check CDN signing keys match between app and CDN
- Check whether the URL has expired and request a fresh authorized one. The helper's expiry value is in minutes; increasing it is a policy choice, not a fix for the wrong signing host/key.
- Verify
USE_APP_URLSenvironment variable is set correctly
3. Image Variants Not Generating
Symptom: Original images upload but variants don't appear Cause: Queue not processing or ImageMagick not installed Solutions:
- Confirm the relevant queue is consuming jobs and inspect the specific failed job through your operator tooling.
- Confirm the processing runtime has Imagick and the required format support.
- Check the source object exists and the job can read/write its configured disk.
- Retry only after identifying the failure and confirming the operation is safe to repeat; use the private operator runbook for worker and recovery commands.
4. Video Processing Stuck
Symptom: Videos remain in "processing" status indefinitely Check: Metadata probing, queue execution, cloud job submission, provider outcome and callback/application are separate failure points Solutions:
- Check FFprobe availability for metadata extraction, plus the submitted Google Cloud job and authenticated callback outcome
- Distinguish a failed probe or submission from a submitted provider job still running. Increasing a PHP worker timeout does not repair a failed provider job or missing callback.
- Inspect the specific failure using operator tooling; timeout configuration and worker recovery belong in the private runbook.
5. Large Upload Not Triggering Processing
Symptom: The browser reports a successful PUT but the model remains waiting_for_upload.
Check the actual object key, disk and bytes, then trace the provisioned authenticated finalization callback. Its registry lookup must resolve the expected model, ID and column, and that configuration must have a status column. A callback acknowledgment for an unrelated or already-transitioned key does not establish readiness. Check callback authentication/response and the owning model's processing outcome separately.
Do not mark the model processing merely to advance the UI: the normal callback uses waiting_for_upload as its start condition, so a premature manual transition can make it skip work. Use the private operator recovery procedure for a diagnosed stuck object rather than dispatching duplicate processing blindly.
Best Practices
1. Always Use Status Tracking
For any model with async processing, use status tracking:
protected $uploadableFileList = [
[
'column' => 'file_path',
'status' => 'upload_status', // Always include this
// ...
],
];
2. Implement Event Listeners
Use custom events when a consumer needs these lifecycle signals. They do not prove that every queued output succeeded; verify the required outputs before advancing a dependent workflow:
// Optional custom lifecycle events; define the event classes for your model.
protected function getImageVariantCompletedEvent(): string
{
return MyModelVariantCompleted::class;
}
protected function getUploadCompletedEvent(): string
{
return MyModelUploadCompleted::class;
}
3. Clean Up on Delete
The deletion hook schedules pending cleanup records; it does not synchronously prove every associated storage object was removed. Verify the cleanup outcome, including custom path schemas:
// This happens automatically, but you can customize
static::deleting(function ($model) {
// Uploadable schedules pending cleanup; check the eventual storage outcome
// Add any additional cleanup here
});
4. Validate File Types
For a multipart-only image endpoint, an explicit feature-specific rule might be:
public function rules(): array
{
return [
'file' => [
'required',
'file',
'mimes:jpg,png,gif',
'max:10240', // Illustrative 10 MiB per-file feature limit (KiB).
],
];
}
The 10 MiB value above is an illustrative product limit, not the transport threshold or a platform-wide recommendation. This file rule accepts uploaded bytes and does not implement the metadata-placeholder/direct-upload protocol. Use the owning endpoint's SafeUploadable contract when supporting that protocol, and separately verify stored content as described below.
5. Use Appropriate Disks
Choose the right disk for your use case:
- Development:
local - Production (private files):
gcswithvisibility => 'private' - Production (public files):
gcs_publicwithvisibility => 'public' - Large uploads: the upload URL is signed using the file definition's disk. The
directdisk serves a separate direct-read helper; choosing it alone does not enable browser direct-upload mode.
6. Optimize Variant Sizes
Choose variant sizes appropriate for your use case:
'variants' => [
'thumbnail' => [128, 128], // Small thumbnails
'card' => [400, 300], // Card displays
'modal' => [1200, 900], // Modal views
'full' => [2048, 2048], // Full-size viewing
],
7. Monitor Queue Performance
- Confirm processing workers are running and consuming the relevant queue; deployment and recovery commands belong in the private operator runbook.
- Monitor failed jobs regularly
- Set up alerts for queue backlog
- Scale workers based on load
8. Cache File Existence Checks
File-existence checks use FileExistenceCache: a per-request memo over shared rememberForever entries, with optional batched preloading. Cached positive and negative results can outlive an external storage change; use the reset helpers when file state changes. This cache is not a fresh storage probe:
// If manually modifying files
$model->resetFileExists('column_name');
// For videos with multiple assets
$model->resetAllVideoFileExists('column_name');
9. Handle Processing Failures Gracefully
Decide how a failed consumer is retried and reconciled before adding a listener. Log enough model/job context to locate the failed operation, avoid logging signed URLs or credentials, and make repeated handling safe. Do not swallow every exception merely to keep other listeners running: that can discard the work a retry was meant to recover.
The built-in jobs have different contracts. ExtractUploadDetailsJob logs extraction failures without rethrowing; CreateMediaTranscoding can rethrow a processing failure. An event or cleared processing flag therefore needs the output/readiness checks described above before a consumer treats media as available.
10. Test Both Upload Modes
Test the actual client and endpoint pair, including:
- Files just below, exactly at and just above the configured threshold. The inspected clients select the large-file branch with
>, so equality alone does not select it. - A selection of small files whose combined size exceeds the threshold. The dropzone can select direct mode from aggregate size; the shared form helper instead inspects each top-level file/first file-list entry.
- Multiple file fields, duplicate original filenames, missing upload URLs and mixed direct/multipart values.
- Allowed and rejected content, declared metadata versus actual stored bytes, and expired or failed signed PUTs.
- Interrupted transfers, lost finalization callbacks and processing failures. Confirm model status and required outputs before marking the file ready.
Performance Optimization
1. Eager Load Relationships
Identify the relationships actually traversed by the model's watermark/path configuration, then eager-load those authorized relationships. The relation names depend on the selected model and configuration; copying an unrelated model's relation chain can fail or load the wrong context.
2. Batch processing and completion
CreateImageVariant implements Laravel's Batchable, but its constructor requires the variant key, variant definition, resolved file definition, original path and watermark definition. The old new CreateImageVariant(...) placeholder was not runnable. Prefer the model's supported processing entry point so it supplies that context and lifecycle flags. Custom batching must deliberately reproduce the required context and distinguish a batch completing from every expected output being usable; do not use an empty constructor sketch as an integration recipe.
3. CDN delivery
Provision CDN origin, signing keys, access policy and domain routing through the owning environment configuration. USE_APP_URLS or a signing variable alone does not create a working CDN or make an object private. The URL helper's adapter/fallback branch and prefix lifetime matter; use an explicit lifetime and verify the served object and authorization boundary. Production provisioning and key rotation stay in private operator runbooks.
4. Optimize Storage Reads
Cache stable metadata and use the existing existence-cache preloading where appropriate. Generate expiring URLs near the authorized request that needs them:
// Lifetime is in minutes; authorization belongs to the owning caller.
$url = $asset->signedUrl('file_name', 5);
Do not cache a 60-minute URL for a full 3,600 seconds without margin: a cache hit near the end can return an almost-expired link. Re-check the helper's actual signing/fallback branch and domain context before designing a shared URL cache.
Security Considerations
1. Validate All Uploads
The owning endpoint must authorize the project/resource and apply its current request rules. SafeUploadable has two distinct branches:
- An
UploadedFileis checked with Laravel'sfilerule and the caller's configuredmax,mimesand/ormimetypesconstraints. - A direct-upload metadata array with
large_uploadchecksSafeFilename, positive numeric declared size and the global hard cap. It does not apply those uploaded-file MIME allowlists to the future stored bytes. A clienttypevalue is not a server MIME inspection.
Where a feature requires a content allowlist, verify the stored object through the owning processing/acceptance path before exposing it. This metadata validator alone does not establish that inspection has occurred. Inspect on the model's configured disk rather than assuming the default disk contains the object.
2. Limit Upload Sizes
LARGE_UPLOAD_THRESHOLD controls transport selection; MAX_LARGE_UPLOAD_FILE_SIZE caps declared direct-upload metadata size. Multipart request rules can impose a different maximum in KiB. Proxy/PHP limits apply to the multipart request body, which includes overhead and may contain multiple files. A successful metadata request does not prove the subsequent stored object matches its declared size. Keep deployment-specific server configuration in the private operator runbook.
3. Use the Correct Serving Boundary for Private Content
Authorize the owning resource and use an appropriately private disk and serving policy. signedUrl($column, 5) requests a five-minute link on supported signing branches, but local/unsupported adapters can return ordinary URLs. directSignedUrl can also return a signed provider URL; a direct provider host is not inherently public. Verify the actual helper branch, expiry and storage access policy rather than classifying every direct URL as unsafe or every method named “signed” as private.
4. Validate Filenames Before Storage
SafeFilename requires a string basename of at most 255 bytes after trimming, rejects empty values, NUL bytes, either path separator and the exact traversal segments ./... It validates rather than rewriting the supplied name. Keep the request validation even when rename is enabled.
With rename => true, the trait generates a random/timestamp basename while retaining the extension. Otherwise it uses the supplied/original basename, truncating a long basename with a hash suffix. Those naming helpers are not a replacement for SafeFilename or content validation. A permissive character-removal regex can also turn different names into the same key or an empty name; do not substitute it for the owning endpoint's validation.
Quick Reference
Common Methods
// File upload
$model->attachFile($uploadedFile, 'column_name', 'custom-name.jpg');
// Get file information
$model->fileName('column_name');
$model->originalFileName('column_name');
$model->mime('column_name');
$model->size('column_name');
$model->path('column_name');
$model->disk('column_name');
// Video-specific
$model->duration('column_name');
$model->resolution('column_name');
// URL generation
$model->url('column_name'); // Ordinary URL after cached existence check
$model->signedUrl('column_name', $minutes); // Temporary URL, or ordinary URL on fallback disks
$model->directSignedUrl('column_name'); // Disk temporary URL; adapter support required
// File existence
$model->fileExists('column_name');
$model->resetFileExists('column_name');
// Processing
$model->processFileUpload('column_name');
$model->processAllFiles();
$model->processingFlag(null, 'column_name'); // Read overall status on metadata models
$model->processingFlag([], 'column_name', 1); // Set overall processing with a configured status column
$model->processingFlag('transcode', 'column_name', 1); // Set a named metadata flag
// Large uploads
$model->returnUploadSignedUrl($metadata, 'column_name');
// Immediate storage-directory deletion; does not delete/clear the model
$model->deleteFile('column_name');
Attachment and deletion side effects
attachFile($uploadedFile, $column, $name, $update = true) stores the file and normally updates the model column, returning that model update's result. With $update = false, it returns the prepared metadata instead; the caller must deliberately persist/integrate it. It is not the same transport as submitting a direct-upload metadata placeholder. With renaming enabled, the configured naming policy takes precedence over the supplied custom name.
deleteFile($column) calls the disk's deleteDirectory() on path($column, false). It can remove the original and sibling outputs in that directory immediately. It does not delete the model row, clear the stored file metadata or return a verified cleanup result. This differs from the model's deleting hook, which schedules pending deletion records. Use the owning authorized operation and reconcile model/cache state; do not call it as a harmless metadata reset or run it against a shared path without checking the directory boundary.
Configuration Quick Start
These are model property fragments, not complete model definitions. Supply the trait, matching columns/casts, relationships, storage configuration and supported processing callbacks. Video watermark configuration does not currently apply a video overlay.
Minimal Configuration (images only):
protected $uploadableFileList = [
[
'column' => 'image',
],
];
Standard Configuration (images with variants):
protected $uploadableFileList = [
[
'class' => 'my-model',
'column' => 'image',
'rename' => true,
'status' => 'upload_status',
'variants' => [
'thumbnail' => [128, 128],
'medium' => [512, 512],
],
],
];
Full Configuration (videos with all features):
protected $uploadableFileList = [
[
'class' => 'my-videos',
'column' => 'video_file',
'disk' => 'gcs',
'rename' => true,
'status' => 'upload_status',
'video' => ['transcode', 'sprite', 'transcription'],
'watermarks' => [
[
'relations' => 'organization.branding',
'file_column' => 'watermark_file',
'settingsRelation' => 'organization.settings',
'opacity_column' => 'watermark_opacity',
'enable_column' => 'watermark_enabled',
],
],
],
];
Additional Resources
- Trait Source:
app/Traits/Uploadable.php - Jobs:
app/Jobs/CreateImageVariant.phpapp/Jobs/CreateMediaTranscoding.phpapp/Jobs/ExtractUploadDetailsJob.php
- Services:
app/Services/TranscoderService.phpapp/Services/VideoIntelligenceService.php
- Request Validation:
app/Http/Requests/StoreProjectAssetRequest.php - Example Models:
app/Models/ProjectAsset.phpapp/Models/SocialStreamPost.phpapp/Models/PluginPageVersion.php
- Frontend Components:
resources/js/Components/AssetUploaderDropzone.vueresources/js/Components/Mod/v2/CardElements/File/AssetPickerFile.vue
- Frontend Stores:
resources/js/Components/Mod/v2/Store/assetPickerStore.jsresources/js/Store/assetStore.js
Verification scope
The documented contracts have source and document-reader review recorded in the repository's docs/file-upload-review-2026-10-14.md and docs/coverage/file-upload-source-snapshot.json. Retained offline checks cover selected request metadata validation, transport helpers, lifecycle/event timing, URL adapter calls, tiny-image variants, media job configuration, picker cache/response behavior, destructive deletion and the minimal custom multipart model. These are separately scoped checks, not a single end-to-end upload suite.
Deployment acceptance remains necessary for actual endpoint permissions, signed storage transfers/content types, callback authentication and delivery, supported media formats/provider outputs, mounted browser controls, cleanup and concurrency. The guide describes observed failure boundaries; it does not certify those deployment outcomes or every possible custom model.