Laravel 11 Download Image from Amazon AWS S3 Bucket

Hello, laravel web developers! In this article, we'll see how to download images from the AWS S3 bucket in laravel 11. In the previous article, we learned about how to upload images in Amazon AWS S3 bucket in laravel 11.

Also, we'll use league/flysystem-aws-s3-v3 composer package to retrieve files from the AWS S3 bucket. So, let's see how to get an image from the s3 bucket in laravel 11.

Step 1: Install the Laravel 11 Application

If you haven't already, create a new Laravel 11 application using the following command.

composer create-project --prefer-dist laravel/laravel laravel-aws-S3-example

 

Step 2: Create S3 Bucket

First, we need to create an AWS S3 bucket and an IAM User to get started. Let's walk through the necessary steps:

  1. Begin by visiting the Amazon Web Services Console and create your AWS account if you don't have one. If you already have an account, simply log in.

  2. Next, navigate to "All Services" and select "S3" under the "Storage" category, which can be found in the menu. Alternatively, you can use the search bar to locate "S3" as shown in the screenshot below. This is where you'll set up your S3 bucket and configure the required settings.

These initial steps are crucial in preparing your AWS environment for image download and storage with Laravel 11

aws-s3-storage-services

3. After selecting "S3" under the "Storage" category. Here, you should click on the "Create Bucket" button to initiate the process of creating a new S3 bucket for your image storage needs.

4. Upon clicking the "Create Bucket" button, you'll be presented with a bucket creation form. In this form, the primary detail you need to provide is the "Bucket name." However, you can customize other settings according to your specific requirements.

After filling in the necessary information, proceed to click the "Create bucket" button located at the bottom of the screen. This action will establish your new S3 bucket, ready to store the images you'll be uploading with Laravel 11

5. To enable secure access to your S3 bucket and the ability to upload files from Laravel, you'll need to create an IAM (Identity and Access Management) User. Follow these steps:

  • Click here to create an IAM User, or alternatively, you can search for "IAM" in the service list, and then select "Users."

Creating an IAM User is essential for managing access permissions and ensuring the security of your AWS resources, including the S3 bucket you've just created. This user will be configured to interact with your Laravel application.

aws-iam-user-create

Click on the “Add users” button as shown above.

6. In the "Add User" form, you will need to provide the following information:

  • User name: Enter a suitable name for your IAM User. This will be used to identify the user, and it's a good practice to choose a name that reflects its purpose or role.

  • Access type: Select "Programmatic access." This option allows the user to interact with AWS services through API calls, which is what you need to enable AWS S3 interactions from your Laravel application.

Once you've filled in this information, proceed by clicking the "Next" button. This will lead you to the next steps in creating the IAM User.

7. In the next step of creating your IAM User, follow these instructions:

  • Select the tab labeled "Attach Existing Policies Directly." This option allows you to directly assign pre-defined AWS policies to your IAM User.

  • From the list of available permissions, find and select "AmazonS3FullAccess." This policy provides your user with full access to Amazon S3, allowing them to list, upload, and manage objects in S3 buckets.

After selecting "AmazonS3FullAccess," click the "Next" button to proceed. This step ensures that your IAM User has the necessary permissions to interact with your S3 bucket.

aws-attach-policies-to-iam-user

8. At this stage, you can optionally add tags to your IAM User for better organization and resource tracking. Tags can help you categorize and manage your AWS resources, but they are not mandatory. If you don't wish to add tags, you can simply skip this step by clicking the "Next" button.

After skipping or adding tags, you'll arrive at the "Review" step. Here, you can review the details you've entered for the IAM User to ensure they are accurate. Once you've verified the information and are satisfied with your selections, click the "Create user" button to complete the user creation process.

9. After successfully creating the IAM User, you will receive a confirmation message, and a list of newly created users will be displayed, similar to the screenshot provided. Within this list, you will find two essential pieces of information:

  • Access Key ID: This is a unique identifier for your IAM User, which will be used in your Laravel application to authenticate with AWS S3.

  • Secret Access Key: This is a secret key that complements the Access Key ID. It should be kept confidential and used to authenticate your Laravel application with AWS S3.

You will need both the Access Key ID and Secret Access Key to configure your Laravel application to connect with your AWS S3 bucket. Make sure to securely store these keys, as they are vital for the integration.

aws-add-user-success-msg

 

Step 3: Install AWS S3 Filesystem Package

To establish a connection between your Laravel application and AWS S3, you'll need to install the Flysystem adapter for the AWS S3 SDK v3.x.

This package simplifies the process of interacting with S3. Open your terminal and run the following command to install the necessary package.

composer require league/flysystem-aws-s3-v3

In your Laravel project, open the .env file and add your AWS S3 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-s3-bucket

If you are running your web app without https protocol then you have to follow this else you will get the aws http error: curl error 60: ssl certificate problem: unable to get local issuer certificate error.

Open the config\filesystems.php and add the 'scheme'  => 'http' in ‘s3’ array like below:

config\filesystems.php

'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,
    'scheme'  => 'http'
],

 

 

Step 4: Create Routes

In your routes/web.php file, define a route that handles the image download.

<?php
 
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ImageController;
 
Route::get('download', [ImageController::class, 'index']);

 

Step 5: Create ImageController

Create a controller that handles the image download. You can generate a controller using Artisan.

php artisan make:controller ImageController

app/Http/Controllers/ImageController.php

<?php
 
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Models\Image;

class ImageController extends Controller
{
    public function index(Request $request) 
    {
        $id = 1;
        $attachment = Image::find($id);
 
        $headers = [
            'Content-Type'        => 'application/jpeg',
            'Content-Disposition' => 'attachment; filename="'. $attachment->name .'"',
        ];
 
        return \Response::make(Storage::disk('s3')->get($attachment->url), 200, $headers);
    }
}

 

 Step 6: Run the Laravel Application

Now, run the following command in your terminal to initiate the development server:

php artisan serve

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS