Sechno
Software Development

How to Set Up Cloud Storage with Laravel 11 and AWS S3

By connecting AWS S3 to Laravel 11, you can easily control how files are stored in the cloud. Set up an S3 bucket, set up Laravel, and use Laravel's Storage API to upload, retrieve, and handle files on S3 with this guide. Perfect for programs that deal with media or a lot of info.

SSechno Team 5 min read 331 views
How to Set Up Cloud Storage with Laravel 11 and AWS S3

AWS S3 is a great choice if you need to store a lot of user-generated content or are making an app that lets people upload files. It's dependable, expandable, and works well with Laravel. Setting up S3 storage has never been easier than it is with Laravel 11. We'll set up AWS S3 with Laravel 11 step by step in this post. We'll also talk about configuration, general use, and some ways to get the most out of your cloud storage.

Why Use AWS S3 for File Storage?

S3, or Amazon Simple Storage Service, is their cloud-based storage service that can hold and get any amount of data. It's great for apps that upload a lot of files or use a lot of media because it instantly scales and lets you manage storage without having to worry about the infrastructure underneath.

Prerequisites

Before we dive in, make sure you have:

  1. A Laravel 11 project set up on your local machine.
  2. An AWS account with permission to create and manage S3 buckets.
  3. Composer installed to manage Laravel dependencies.

Step 1: Set Up Your S3 Bucket on AWS

First, let’s set up the actual S3 bucket where your files will live.

  1. Create a New Bucket:
    • Sign into your AWS Console and head to the S3 section.
    • Click Create bucket.
    • Give your bucket a unique name (bucket names need to be globally unique).
    • Choose a region close to where most of your users are for better performance.
    • Click Create after configuring permissions and settings.
  2. Set Up Access Credentials:
    • Open the IAM (Identity and Access Management) section in AWS.
    • Go to Users > Add User and create a new user with Programmatic access.
    • Attach the AmazonS3FullAccess policy, which grants permissions to work with S3.
    • Save the Access Key ID and Secret Access Key somewhere secure. You’ll need these later.

Step 2: Install the AWS SDK for PHP

To let Laravel talk to S3, you’ll need the AWS SDK for PHP. Laravel doesn’t automatically include this, so run this command to install it:

composer require aws/aws-sdk-php

Step 3: Add AWS S3 Credentials to the .env File

With the AWS SDK ready, let’s configure Laravel to connect to your bucket. Open your .env file and add the following lines (replacing the placeholders with your actual credentials):

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
AWS_URL=https://your-bucket-name.s3.amazonaws.com

This tells Laravel how to authenticate and connect to your S3 bucket.

Step 4: Update Laravel’s Filesystem Configuration

Next, open the config/filesystems.php file in your project. Laravel has a built-in disk configuration for S3, but let’s tweak it to make sure it uses the settings from our .env file:

'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'),
    'visibility' => 'public', // Set to 'private' if you don’t want the files to be publicly accessible
],

This setup tells Laravel that we’re using S3 as a storage driver and where it can find the credentials and configuration.

Step 5: Testing the S3 Integration

Let’s test it out by creating a small function to upload a file to S3. Using Laravel’s Storage facade makes it simple to handle files, whether you’re uploading, downloading, or deleting them.

Here’s an example of a simple file upload endpoint:

use Illuminate\Support\Facades\Storage;
 
public function uploadToS3(Request $request)
{
    if ($request->hasFile('file')) {
        $file = $request->file('file');
        $path = Storage::disk('s3')->put('uploads', $file);
 
        return response()->json([
            'message' => 'File uploaded successfully',
            'path' => Storage::disk('s3')->url($path),
        ]);
    }
 
    return response()->json(['message' => 'No file uploaded'], 400);
}

This function checks if there’s a file in the request, then uploads it to an uploads folder in your S3 bucket. If the upload succeeds, it returns the URL of the uploaded file.

Step 6: Working with Files in S3

Once files are uploaded, you can use Laravel’s Storage facade to interact with them. Here are some common actions:

  • Retrieve a File URL:
$url = Storage::disk('s3')->url('uploads/filename.jpg');
  • Delete a File:
Storage::disk('s3')->delete('uploads/filename.jpg');
  • Check if a File Exists:
$exists = Storage::disk('s3')->exists('uploads/filename.jpg');

These functions make working with files on S3 seamless and integrate with Laravel’s file storage system.

Step 7: Pro Tips for Optimizing S3 Storage

  1. Use Lifecycle Rules: You can set rules in S3 to move files to a cheaper storage class or remove them after a certain amount of time. Perfect for keeping backups or old files for future reference.
  2. Add Caching and a CDN: To speed up file load times, enable caching headers for files that are viewed often and think about using Amazon CloudFront as a CDN.
  3. Change who can see a file: In your filesystems.php config file, change the access parameter to public or private, depending on what you need. Direct URLs let you get to public files, but you need to be logged in to see secret files.

Wrapping Up

You've successfully set up S3 in Laravel 11 by following these steps! AWS S3 not only makes managing files scalable, but it also makes your Laravel app more flexible and reliable. AWS S3 is a great choice whether you're making an app with lots of media or just need a safe place to store user files.

Happy coding, and enjoy the cloud!

Was this helpful?

Share this post

Comments (0)

Want to join the conversation?

Log in or sign up to leave a comment and share your thoughts.

Log in to Comment