mattmy / laravel-file-magic
Securely accept, validate, store, query, download, and delete files through one fluent Laravel API.
Requires
- php: ^8.3
- ext-fileinfo: *
- guzzlehttp/psr7: ^2.7 || ^3.0
- illuminate/console: ^12.0|^13.0
- illuminate/contracts: ^12.0|^13.0
- illuminate/database: ^12.0|^13.0
- illuminate/filesystem: ^12.0|^13.0
- illuminate/http: ^12.0|^13.0
- illuminate/support: ^12.0|^13.0
- psr/http-message: ^1.1|^2.0
- symfony/http-foundation: ^7.0|^8.0
- symfony/mime: ^7.0|^8.0
Requires (Dev)
- intervention/image: ^4.0
- larastan/larastan: ^3.0
- laravel/pint: ^1.29
- mrpunyapal/peststan: ^0.2.12
- orchestra/testbench: ^10.0|^11.0
- pestphp/pest: ^3.0|^4.0
- pestphp/pest-plugin-laravel: ^3.0|^4.0
- phpstan/phpstan-mockery: ^2.0
Suggests
- ext-curl: Required only when importing files from HTTP(S) URLs.
- ext-zip: Required only when creating ZIP downloads.
- intervention/image: Required only when using image resizing and encoding.
Provides
None
Conflicts
- intervention/image: <4.0
Replaces
None
README
FileMagic stores files on Laravel Filesystem disks and returns an Eloquent StoredFile record.
Use FileMagic::find() to look up files for reading, downloading, or deletion.
What you can do
- Store uploaded files, local files, content, Base64, and remote HTTP(S) files.
- Generate TXT, JSON, or CSV. Store content generated by your app with a trusted MIME type.
- Set size and MIME limits, choose how to handle filename collisions, and resize supported images.
- Save metadata and associate files with Eloquent models.
- Find files by ID, UUID, or model. Pass an array or Laravel Collection for batch lookups.
- Generate URLs, download a set of files as a ZIP, or delete files in batches.
- Audit database records whose files are missing from storage.
Requirements
- PHP 8.3–8.x
- Laravel 12 or 13
- PHP
ext-fileinfo - A configured Laravel Filesystem disk and database connection
Remote files need PHP ext-curl. Image resizing additionally needs intervention/image 4.x
and PHP GD or Imagick. ZIP downloads need PHP ext-zip.
Installation
composer require mattmy/laravel-file-magic php artisan vendor:publish --tag=file-magic-migrations php artisan migrate
To change the defaults, publish the configuration with php artisan vendor:publish --tag=file-magic-config.
If you need image resizing, also install Intervention Image 4 and enable PHP GD or Imagick:
composer require intervention/image:^4.0
Quick start
Validate the upload and check the user's permissions before running this example.
use Mattmy\FileMagic\Facades\FileMagic; $file = FileMagic::fromUpload($request->file('document')) ->onDisk('local') ->inDirectory('documents') ->named('contract') ->store(); return FileMagic::find($file)->download();
Store files from different sources
FileMagic::fromUpload($uploadedFile)->store(); FileMagic::fromPath($trustedPath)->store(); FileMagic::fromContent($contents, 'report.pdf')->store(); FileMagic::fromGeneratedContent($dxfContents, 'drawing.dxf', 'image/vnd.dxf')->store(); FileMagic::fromBase64($base64, 'avatar.png')->store(); FileMagic::fromUrl('https://example.com/manual.pdf')->store();
Generate documents with the same storage options:
FileMagic::text('Hello')->named('message')->store(); FileMagic::json(['status' => 'ready'])->named('status')->store(); FileMagic::csv($rows)->named('report')->store();
fromContent() detects the MIME type from the bytes. With fromGeneratedContent(), FileMagic
uses the supplied MIME type when Symfony can map it to an extension. Use it only for content
whose format your application guarantees. If the MIME type is omitted or unmapped, FileMagic
falls back to fromContent().
// Unsafe: neither the bytes nor MIME type are application-controlled. FileMagic::fromGeneratedContent($request->getContent(), null, $request->header('Content-Type'));
For a raw request body, use fromContent($request->getContent()). Both methods take the complete
$contents string in PHP memory. For large files, use an upload, a local path, or a URL as appropriate.
Configure a file
use Mattmy\FileMagic\Enums\CollisionPolicy; use Mattmy\FileMagic\Enums\FileVisibility; $file = FileMagic::fromUpload($uploadedFile) ->onDisk('s3') ->inDirectory('accounts/42/contracts') ->named('signed-contract') ->visibility(FileVisibility::Private) ->onCollision(CollisionPolicy::Unique) ->maxSize(10 * 1024 * 1024) ->allowMimeTypes(['application/pdf']) ->withMetadata(['category' => 'contract']) ->ownedBy($user) ->store();
named() keeps dots in the base name and appends the MIME-derived extension. For example,
a text file named report.txt saves as report.txt.txt if the name is available.
Use resizeImage() to shrink supported images before storage.
$image = FileMagic::fromUpload($uploadedImage) ->resizeImage(maxWidth: 1200, quality: 80) ->store();
Find and use stored files
$file = FileMagic::find($uuid)->one(); $files = FileMagic::find([$firstId, $secondUuid])->get(); $exists = FileMagic::find($uuid)->exists(); $url = FileMagic::find($uuid)->url(); $temporaryUrl = FileMagic::find($uuid)->temporaryUrl(); $customTemporaryUrl = FileMagic::find($uuid)->temporaryUrl(now()->addMinutes(15)); $contents = FileMagic::find($uuid)->contents(); $stream = FileMagic::find($uuid)->readStream(); return FileMagic::find($uuid)->download();
Reuse the same FileQuery when you perform several operations on the same targets. For large files,
use readStream() and close the stream when you finish. contents() loads the entire file into memory.
Safety and resource limits
FileMagic checks the decoded size of Base64 input before decoding. It keeps the encoded string in
memory and writes decoded bytes to a temporary file in chunks. Use relative storage paths with /
separators. FileMagic checks size and MIME limits on the original image and again if processing
changes the output.
ZIP downloads and deletion
return FileMagic::find($targets)->downloadZip('documents');
$deleted = FileMagic::find($targets)->delete();
Your application must authorize every operation, including access to each file in a ZIP download.
When enabled, path locks coordinate stores, batch deletes, and audit cleanup through the same
cache backend while the locks are valid. Direct StoredFile::delete() and external writes bypass these locks.
Consistency audits
Check whether the files referenced by database records still exist.
php artisan file-magic:audit
The audit is read-only by default. With --delete-missing-records, it checks the record and file
again before removing a record whose file is still missing. Those checks run under path locks when
locking is enabled. On remote disks, each existence check can add latency and request charges.
Handle errors
All package exceptions extend FileMagicException:
use Mattmy\FileMagic\Exceptions\FileMagicException; try { $file = FileMagic::fromUpload($uploadedFile)->store(); } catch (FileMagicException $exception) { report($exception); }
Documentation
See the FileMagic documentation for guides and the API reference.
Report vulnerabilities privately according to SECURITY.md.
License
FileMagic is open-source software licensed under the MIT License.