Amazon S3 (Simple Storage Service) is one of the most reliable and scalable cloud storage services available. It allows developers to store and retrieve files of any size securely. Integrating AWS S3 with a Laravel application provides a seamless way to manage file storage in the cloud.
In this guide, we’ll walk you through the process of configuring and storing data in an AWS S3 bucket using Laravel step by step.
Introduction
Laravel comes with built-in support for Amazon S3 through the Flysystem integration, making it easier to upload, retrieve, and manage files directly from your application. By the end of this tutorial, you’ll be able to upload files to S3, fetch files, list all files, and even delete files directly from your Laravel app.
Before we begin, ensure that you have the following prerequisites:
- An AWS account with access to S3.
- A Laravel application (Laravel 10 recommended).
- Composer installed on your system.
Step 1: Install AWS SDK for PHP
Laravel uses the league/flysystem-aws-s3-v3
package to interact with AWS S3. This package may already be installed, but if not, you can install it using Composer:
composer require league/flysystem-aws-s3-v3
Step 2: Configure AWS S3 in Laravel
After installing the package, configure your AWS credentials in the Laravel application.
1. Add AWS credentials in .env
file
Open the .env
file in your Laravel project and add the following details:
AWS_ACCESS_KEY_ID=your-access-key-id
AWS_SECRET_ACCESS_KEY=your-secret-access-key
AWS_DEFAULT_REGION=your-region
AWS_BUCKET=your-bucket-name
Make sure you replace the placeholders with your actual AWS credentials.
2. Update config/filesystems.php
Next, open the config/filesystems.php
file and configure the S3 disk:
'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'),
],
Step 3: Upload Files to AWS S3 Bucket
Laravel’s Storage
facade makes it easy to upload files to your S3 bucket.
Upload a File
use Illuminate\Support\Facades\Storage;
Storage::disk('s3')->put('folder/filename.txt', 'File content goes here');
Retrieve a File
$file = Storage::disk('s3')->get('folder/filename.txt');
Get All Files from a Directory
$files = Storage::disk('s3')->files('folder');
Delete a File
Storage::disk('s3')->delete('folder/filename.txt');
Conclusion
In this article, we explored how to store data in an AWS S3 bucket in Laravel. By integrating S3 with Laravel, you can seamlessly upload, retrieve, list, and delete files in the cloud, improving the scalability and efficiency of your application.
Following these steps will ensure a smooth integration, allowing you to leverage the power of Amazon S3 for secure and reliable file storage in your Laravel projects.
If you encounter any issues, double-check your configuration or consult the Laravel S3 documentation