The upload method simplifies file handling in Laravel by providing a fluent interface for file uploads. To get started, install the package via Composer:
composer require vendor/package-name
Publish the config file (if applicable) and register the service provider in config/app.php. The first use case involves handling file uploads from a form:
use Vendor\PackageName\Facades\FileHandler;
public function uploadFile(Request $request)
{
$file = $request->file('file_input');
$result = FileHandler::upload($file)
->to('uploads/documents') // Destination path
->withName('custom_name.pdf') // Optional: Rename file
->withMetadata(['user_id' => auth()->id()]) // Optional: Attach metadata
->store();
return response()->json($result);
}
Check the package's README.md for default configurations (e.g., disk settings, allowed MIME types) and the config/package-name.php file for customization options.
Use the upload() method for standard file handling:
FileHandler::upload($request->file('avatar'))
->to('avatars/users')
->store();
Leverage method chaining for complex uploads:
FileHandler::upload($file)
->validate(['max_size' => '2mb', 'mimes' => 'pdf,docx']) // Validate before upload
->to('documents/{year}/{month}', ['year' => date('Y'), 'month' => date('m')]) // Dynamic paths
->withName('invoice_{id}.pdf', ['id' => $invoice->id]) // Dynamic naming
->withMetadata(['client_id' => $client->id, 'type' => 'invoice'])
->store();
The package integrates seamlessly with Laravel's Storage facade. Specify a custom disk:
FileHandler::upload($file)
->to('backups')
->onDisk('s3') // Use S3 instead of default
->store();
Process arrays of files (e.g., from <input type="file" multiple>):
foreach ($request->file('files') as $file) {
FileHandler::upload($file)
->to('uploads')
->store();
}
Trigger actions after upload (e.g., generate a thumbnail):
$upload = FileHandler::upload($file)
->to('images')
->store();
if ($upload->success()) {
$this->generateThumbnail($upload->path);
}
Disk Configuration:
Ensure the specified disk (e.g., s3, local) is properly configured in config/filesystems.php. Missing configurations will throw InvalidArgumentException.
Validation Timing:
Validation (e.g., validate()) runs before the upload. Skipping validation may lead to silent failures or security risks.
Dynamic Paths:
Use curly braces {} for dynamic path segments (e.g., to('users/{id}')). Unescaped values may cause path injection vulnerabilities.
Metadata Serialization: Metadata is stored as JSON. Ensure all values are JSON-serializable (e.g., avoid passing objects directly).
Check Upload Logs:
Enable debug mode (config('package-name.debug' = true)) to log upload attempts and failures to storage/logs/package-name.log.
Validate File Existence:
Always check $file->isValid() before passing to FileHandler::upload() to avoid InvalidArgumentException.
Test with Small Files First: Start with small files (e.g., <100KB) to rule out disk/permission issues before testing large uploads.
Custom Storage Drivers:
Extend the package by adding support for new storage drivers via the StorageDriver interface:
namespace Vendor\PackageName\Extensions;
use Vendor\PackageName\Contracts\StorageDriver;
class CustomDriver implements StorageDriver {
public function store($file, $path, $metadata) { ... }
public function url($path) { ... }
}
Register the driver in config/package-name.php under drivers.
Pre/Post Upload Hooks: Bind events to extend upload behavior:
FileHandler::upload($file)
->onBeforeUpload(function ($file) {
// Pre-upload logic (e.g., resize image)
})
->onAfterUpload(function ($result) {
// Post-upload logic (e.g., send notification)
})
->store();
Override Default Config:
Publish the config file (php artisan vendor:publish --tag=package-name-config) and customize:
'default_disk' => 's3',
'allowed_mimes' => ['pdf', 'jpg', 'png'],
'max_size' => '10mb',
Fallback for Missing Files:
Handle cases where $request->file('key') returns null:
$file = $request->file('avatar') ?? throw new \InvalidArgumentException('No file uploaded.');
How can I help you explore Laravel packages today?