Laravel File Upload to S3: Step-by-Step Guide (2026)

Master Laravel file upload to S3 with step-by-step setup, secure code, and error handling. Learn to configure, validate, and serve files using Amazon S3.

Uploading files to S3 in Laravel lets you store user data securely and reliably in the cloud, enabling robust file management, scalability, and global availability. The fundamental process is to configure the S3 disk in Laravel's filesystem configuration, then leverage the Storage facade's put, putFile, or store methods to push files directly. This guide walks you through practical Laravel S3 file upload setup, verification and error prevention, as well as efficient handling strategies based on real production deployments (Laravel 11+ and PHP 8.3+).

Prerequisites for Laravel File Upload to S3

Before we get started, you should have the following set up to ensure seamless Laravel file upload to S3 workflow:

1. A Laravel 11 (or higher) project, running on PHP 8.3+. 2. An AWS S3 bucket created via the AWS console. Make sure you generate IAM credentials (Access Key and Secret) via a user or role, not your root account. 3. The IAM user or role should have at minimum the PutObject and GetObject permissions for your S3 bucket. Add DeleteObject if you want to allow deletions. For extra security, use bucket policies to tightly scope these permissions (see AWS docs for up-to-date policy JSON). 4. The AWS PHP SDK (via Composer). Laravel includes league/flysystem-aws-s3-v3 as the default S3 driver. Confirm it's installed with Composer (see next section). 5. Your APP_URL configured to HTTPS in your .env file, especially if you're using signed URLs or serving sensitive/private file downloads. 6. You should have a strong internet connection, and access to modify config/.env variables for your application. 7. (Optional but strongly recommended) Enable versioning and access logging on your S3 bucket for additional security and rollback capabilities.

  • Laravel 11+ with PHP 8.3+
  • AWS S3 account and at least one bucket
  • IAM user or role with appropriate S3 permissions
  • Internet connection
  • Configurable .env and config/filesystems.php access

How to Set Up Laravel S3 Storage Configuration

To enable Laravel file upload to S3, configure the S3 disk in your application's filesystem. This primarily involves settings in your .env file and config/filesystems.php.

First, ensure the S3 driver is present. Laravel includes the league/flysystem-aws-s3-v3 package by default, but you can install or update to the latest version:

  • Check and set your AWS credentials in .env (never commit these to git):
composer require league/flysystem-aws-s3-v3

Add the following to your .env file, replacing placeholder values with your actual AWS credentials. These values are required for seamless Laravel file upload to S3.

  • Ensure the 's3' disk is configured in config/filesystems.php. Below is a common setup for the 's3' disk:
AWS_ACCESS_KEY_ID=your-iam-access-key
AWS_SECRET_ACCESS_KEY=your-iam-secret-key
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=your-bucket-name
AWS_URL=https://your-bucket-name.s3.amazonaws.com
AWS_USE_PATH_STYLE_ENDPOINT=false
AWS_ENDPOINT=
  • Consider setting different buckets or paths for different environments (development, staging, production)
  • Never hard-code sensitive credentials; always use environment variables
's3' => [
    'driver' => 's3',
    'key'    => env('AWS_ACCESS_KEY_ID'),
    'secret' => env('AWS_SECRET_ACCESS_KEY'),
    'region' => env('AWS_DEFAULT_REGION'),
    'bucket' => env('AWS_BUCKET'),
    'url'    => env('AWS_URL'),
    'endpoint' => env('AWS_ENDPOINT'),
    'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
],

How to Upload Files to S3 in Laravel

Laravel's Storage facade makes S3 uploads almost feel local. The preferred methods are put, putFile, store, and storeAs. All leverage Laravel's abstraction for reliable cloud uploads, validation, and storage integration. Here's a controller method example using a standard request upload workflow:

  • Always validate file uploads for type (mimes), size, etc.
  • Use storeAs for controllable file naming and folder structure
  • Save only the S3 path (not full URL) in your database
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

public function upload(Request $request) {
    $request->validate([
        'file' => 'required|file|mimes:jpg,jpeg,png,pdf,doc,docx|max:10240' // 10MB limit
    ]);

    // Create unique file name
    $userId = $request->user() ? $request->user()->id : 'guest';
    $filename = uniqid().'.'.$request->file('file')->getClientOriginalExtension();
    $path = "uploads/user-{$userId}/{$filename}";

    // Store file on S3
    $s3Path = $request->file('file')->storeAs(
        "uploads/user-{$userId}",
        $filename,
        's3'
    );

    // Get public (or signed) URL
    $url = Storage::disk('s3')->url($s3Path);

    return response()->json([
        'path' => $s3Path,
        'url'  => $url
    ]);
}

Advanced: S3 Multipart Uploads and Large Files

By default, the above code works for files up to your PHP (upload_max_filesize) and S3 single-upload limits. For very large files (100MB+), direct server uploads may hit PHP timeouts. To support large Laravel file uploads to S3, consider one of these strategies:

1. **Multipart uploads**: Use AWS's multipart upload API (requires custom code or a package, e.g. league/flysystem-aws-s3-v3 supports this automatically in recent versions; for advanced control, use the AWS SDK directly).

2. **Direct-to-S3 uploads via the browser**: For very large or numerous file uploads, generate signed upload policies and let the user's browser upload straight to S3 using the AWS JS SDK or similar. Store resulting S3 paths in your database via an API callback.

3. **Background processing**: Queue the file for background upload (see Laravel queues/jobs or Laravel Horizon) if you want to offload or retry failed uploads.

Reference: See the official AWS documentation and Flysystem/Laravel docs for up-to-date recommendations and limitations.

Laravel File Validation and Security Considerations

Strong file upload validation is critical. To ensure only intended files reach S3:

- Strictly validate mime types and extensions (`mimes:jpg,png,pdf,doc,docx` or, for better accuracy, use `mimetypes:`) - Enforce file size limits (max:10240 for 10MB, adjust as needed) - Never trust the original filename; generate random or UUID-based names - Sanitize user-provided metadata and metadata tags - If your app stores files for long periods, consider scanning uploads for malware using external tools or AWS Lambda triggers

Example validation snippet:

$request->validate([
    'file' => 'required|file|mimes:jpg,jpeg,png,pdf|max:10240',
]);

Laravel File Upload to S3 Best Practices

Uploading files directly to S3 is fast, cost-effective, and scales well — but you must follow best practices:

- **Validate uploads strictly** (file type, size, mime) to block abuse or malware - **Organize S3 keys ("paths")** logically, e.g. 'uploads/user-42/resume.pdf'. This makes user file cleanup, exports, or privacy deletions easier. - **Use randomized or UUID-based file names**; never use raw user input. Including a timestamp (Carbon::now()->timestamp) enhances uniqueness; UUIDs provide better collision resistance. - **Store only file paths (keys) in the database**; generate URLs as needed with Storage facade - **For high concurrency or large files, consider chunked/multipart uploads or direct browser-to-S3 patterns (see above)** - **Monitor upload errors, log them to your error tracking system, and respond with friendly messages** - **Enable server-side encryption on your S3 bucket** for sensitive files - **Configure S3 lifecycle rules** to delete old/unnecessary files and save costs.

Example folder structure: - uploads/user-42/2024-06-07/report.pdf - uploads/user-51/photos/87132e0e.jpg

  • Validate file content, not just extension (use a library like getimagesize for images).
  • Organize S3 storage using user IDs, timestamps, or models.
  • Enable S3 encryption (AES-256 or AWS-KMS) if handling sensitive data.
  • Automate S3 object versioning for accident recovery.
  • Set S3 lifecycle rules for archival or deletion to optimize costs.

Handling Common Laravel S3 File Upload Errors

S3 and Laravel integration is robust but not always error-free — especially when first configuring uploads or deploying to new environments. Common Laravel file upload to S3 errors and solutions include:

  • Missing credentials: Ensure AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are present, valid, and not expired.
  • Permission denied (AccessDenied): Confirm your IAM user/role can perform PutObject, GetObject (and optionally DeleteObject) on the S3 bucket via both IAM and bucket policy.
  • The "s3" disk is not configured: Check config/filesystems.php and ensure 's3' disk exists and is correct for current APP_ENV.
  • SSL certificate errors: If on legacy PHP/OpenSSL, set AWS_VERIFY=true in .env or update your CA certs.
  • Region mismatch: Ensure AWS_DEFAULT_REGION matches your bucket's actual region.
  • Timeouts on large file uploads: Check PHP max_execution_time and upload_max_filesize, or use multipart uploads.
// Example error handling
try {
    $path = $request->file('file')->store('uploads', 's3');
} catch (\Exception $e) {
    report($e); // Log error for security/auditing
    return response()->json(['error' => $e->getMessage()], 500);
}

// Typical raw error:
// Illuminate\Filesystem\FilesystemAdapter::put(): Unable to write file at location [uploads/file.jpg]. Reason: AccessDenied (client): Access Denied

Testing and Troubleshooting Your S3 Integration

After setting up Laravel file upload to S3, verify your configuration in development and staging before deploying to production:

- Use `php artisan tinker` to run Storage::disk('s3')->put('test.txt', 'hello world') and confirm it appears in your bucket. - Log your upload URLs and S3 response codes for auditing. - Use AWS S3 console to check upload times, object metadata, and permissions. - If deploying to Docker or cloud CI, double-check .env variables are loaded at runtime.

In production, monitor failed uploads with Laravel's logging and error reporting tools, such as Sentry, Bugsnag, or Honeybadger.

How to Use S3 Signed URLs in Laravel

Sometimes you want to allow users to download private S3 files (non-public). Signed URLs (temporary URLs) let you generate time-limited, secure links to specific files.

Here's how to generate a download link that's valid for 5 minutes:

// Assuming $path is your S3 path (e.g., uploads/doc.pdf)
use Illuminate\Support\Facades\Storage;

$url = Storage::disk('s3')->temporaryUrl($path, now()->addMinutes(5));

You can tune the expiry and add optional request parameters. For large files, consider increasing the timeout. Remember, anyone with the signed URL can access the file until it expires.

Frequently Asked Questions About Laravel File Upload to S3

Here's a quick roundup of what developers usually ask when working with Laravel file upload to S3. See [Laravel Storage Docs](https://laravel.com/docs/filesystem) and [AWS S3 Docs](https://docs.aws.amazon.com/s3/) for further details.

Security and Cost Optimization Tips for Laravel S3 Uploads

1. **Limit Permissions**: Always use the least-privilege principle for IAM users or roles. Never use your root AWS credentials for production in Laravel file upload to S3. 2. **Enable Encryption**: Choose 'AES256' or KMS Managed Keys for server-side S3 encryption, either in your bucket policies or via Laravel's configuration. 3. **Monitor Usage**: Use CloudWatch metrics to watch for unexpected spikes (potential abuse or bugs) in S3 usage. 4. **Optimize Storage Costs**: Set lifecycle policies to transition obsolete files to S3 Glacier or delete them after a certain age. 5. **Secure Public Access**: For most file uploads, keep S3 bucket/policy private; serve public files only via signed URLs or with explicit, limited 'public-read' ACL when absolutely necessary.

  • Regularly review IAM and S3 bucket policies for unnecessary exposure.
  • Remove abandoned or transient files periodically to reduce cost.
  • Log all upload and access events for auditing.

Conclusion: Laravel S3 Uploads Done Right

Getting file uploads to S3 working securely and reliably in Laravel is straightforward once you've set up your S3 disk and established solid upload and validation logic. The best practices reviewed — from validating uploads, to organizing file paths, to leveraging signed URLs for secure downloads — bring both scalability and maintainability to your project. Remember to keep your AWS keys secret and environment-specific, always test throughout development and before production, and continuously monitor your storage usage and costs. After you've deployed this workflow a few times, Laravel file upload to S3 will be a rock-solid part of your cloud application stack.

Frequently asked questions

How do I upload a file to S3 using Laravel?

Set up your S3 credentials in .env, ensure the 's3' disk is configured in config/filesystems.php, then use `$request->file('file')->store('uploads', 's3')` or `Storage::disk('s3')->put($path, $contents)` in your controller. Always validate your uploads first.

Why does my Laravel S3 upload fail with Access Denied?

Your IAM user or role likely lacks PutObject permission on the S3 bucket. Double-check both your IAM policy and the bucket policy to ensure 's3:PutObject' access (and optionally GetObject/DeleteObject as needed) is granted to the relevant IAM principal and bucket. Use the AWS IAM Policy Simulator for troubleshooting.

How do I display/download S3 files in Laravel?

For public files, save the S3 path (key) and use `Storage::disk('s3')->url($path)`. For private files, use `temporaryUrl` to generate a signed (temporary) download link, which is secure and time-limited. You may also proxy the file through your app if you need additional access control or logging.

Can I upload large files to S3 from Laravel?

Yes. For files larger than your PHP `upload_max_filesize` or web server timeout, use S3 multipart uploads (supported by Flysystem, or via AWS SDK) or use a direct-to-S3 front-end strategy. This bypasses PHP upload limits and is highly scalable. Consider providing upload progress for users on large uploads.

Is storing S3 file URLs or paths better in Laravel?

Always store only the S3 path (key) in your database. Generate URLs dynamically using `Storage::disk('s3')->url($path)` for public reads or `temporaryUrl` for private access. This gives you flexibility to reorganize your bucket, change region or domain, or rotate keys without touching application data.

How do I handle S3 object deletion in Laravel?

Use `Storage::disk('s3')->delete($path)` to delete a file. Ensure your IAM role/user has `s3:DeleteObject` permission on the target bucket. For batch deletes, use `Storage::disk('s3')->delete(['path1', 'path2'])`.