S3-Storage

Detailed documentation and implementation guides.

S3 File Service Documentation

Overview

The S3 File Service provides a robust interface for handling file uploads and storage using AWS S3. This service is implemented in the S3FileService class and uses a fluent interface for easy file handling and metadata configuration.

Configuration

Environment Variables

Add these variables to your .env file:

FILESYSTEM_DISK=s3
AWS_ACCESS_KEY_ID=your_access_key
AWS_SECRET_ACCESS_KEY=your_secret_key
AWS_DEFAULT_REGION=your_region
AWS_BUCKET=your_bucket_name

Usage Example

use Modules\Attachment\Service\S3FileService;

// Upload a file with metadata using fluent interface
S3FileService::file($request->file('document'))
    ->display_name('Custom Display Name')
    ->type_id(1)
    ->type_name('document')
    ->model('App\Models\Document')
    ->model_id(123)               
    ->path('custom/path')
    ->store();

// Delete a file
S3FileService::delete('path/to/file', 'filename.ext');

Field Requirements

Required Fields

These fields MUST be set before calling store():

  • file: The uploaded file (passed to ::file() method)
  • model: The fully qualified class name of the related model
  • model_id: The ID of the related model record
  • type_id: The type identifier
  • type_name: The name of the type

Optional Fields

  • display_name: Custom display name
    • If not set, defaults to the original filename
  • path: Custom storage path
    • If not set, defaults to 'attachments'

Auto-Generated Fields

These fields are automatically handled by the service:

  • fileName: Generated using random string + timestamp + extension
  • extension: Extracted from the original file
  • originalName: Taken from the uploaded file

Key Features

  1. Fluent interface for easy configuration
  2. Secure file name generation
  3. Automatic file metadata extraction
  4. Required field validation
  5. AWS S3 integration
  6. Comprehensive error handling

Error Handling

The service throws S3FileServiceException in the following cases:

  • Invalid file upload
  • Missing required fields (model, model_id, type_id, type_name)
  • S3 storage failures
  • File not found (when deleting)
  • General storage errors

Best Practices

  1. Always wrap store() and delete() calls in try-catch blocks
  2. Use meaningful type names and IDs for better organization
  3. Group related files using the path option
  4. Validate file uploads before processing
  5. Keep track of stored file paths for future reference