codeflextech / laravel-uploader
Reusable Laravel uploader with DB tracking, polymorphic relations, S3 support & optimization
Requires
- php: ^8.1
- intervention/image: ^2.7
README
A production-ready Laravel file uploader with:
- Polymorphic relations
- Public & private files
- Local / S3 support
- Image optimization
- Auto cleanup on model delete
- Multiple File Types Support
Installation
composer require codeflextech/laravel-uploader
## Configuration
Publish the config file to customize defaults:
```bash
php artisan vendor:publish --tag=uploader-config
Key Config Options (config/uploader.php)
table_name: The database table name (default:files). Can be set viaUPLOAD_TABLE_NAMEenv var.disk: Default storage disk (e.g.,public,s3).folder: Default folder name inside the disk (default:uploads).structure: Date structure for organized files (default:year/month/week).visibility: File visibility (publicorprivate).optimize_images: Auto-resize images (boolean).
Direct Public Uploads
By default, files are stored in storage/app/public and symlinked. If you want to upload directly to the public/ folder (bypassing storage/), you can define a custom disk.
-
Add to
config/filesystems.php:'public_uploads' => [ 'driver' => 'local', 'root' => public_path('uploads'), // Uploads to public/uploads 'url' => env('APP_URL').'/uploads', 'visibility' => 'public', ],
-
Use it in your upload:
$user->upload($file, ['disk' => 'public_uploads']);
Basic Usage
1. Add Trait to Model
Add the HasFiles trait to any model that should have files attached (e.g., User, Post, Product).
use CodeFlexTech\Uploader\Traits\HasFiles; class User extends Authenticatable { use HasFiles; }
2. Upload a File
Use the FileUploader facade or class to handle uploads.
$user->upload( $request->file('avatar'), [ 'folder' => 'avatars', 'disk' => 'public', 'type' => 'profile_pic' ] );
Advanced Usage: File Types & Validation
You can categorize uploads by type (e.g., 'resume', 'profile_pic').
1. Upload with Type
Pass the type in the options array. If omitted, it defaults to 'file'.
$user->upload($file, ['type' => 'resume']);
2. Replacing Files
By default, the upload() method enforces a 1-to-1 relationship per type.
If a user already has a 'profile_pic' and uploads a new one, the old file will automatically be deleted from storage and the database before the new one is saved.
3. Retrieve Files by Type
The HasFiles trait provides helper methods:
// Get all resumes $resumes = $user->filesByType('resume')->get(); // Get the latest profile picture $pic = $user->latestFile('profile_pic');
License
MIT