How To File Upload AWS s3 Bucket In Laravel 9

  • 03-08-2022
  • 975
  • Laravel 9
  • Haresh Chauhan

Image upload on s3 bucked in laravel; s3 provides the best bucket service for managing your project's large number of files and users data. If your project is large and wants to secure store your users data on the s3 amazon bucket. This post will help you how to upload s3 bucket file in laravel.

Once you create your bucked in your s3, You will get all credentials from there. Allow bucked to write permission.

In this post, I will tell you how to upload files on s3 bucked in laravel with the help of the Storage class. This is very simple and max three to four lines of code. You just pasted your credentials and send the file to s3 bucked that's it.

So let's start with how to upload images or files on amazon s3 bucket in laravel.

Aws Config Setup

Set your AWS configuration in .env file. This all configuration must be required to upload the file on AWS server.

.env
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=
AWS_BUCKET=
AWS_URL=

Image Upload

The first post request receives from the client side. Add prefix folder name, This will be the path of your image. It will create a folder `images`. Create your storage path.

Find your extension from the request payload file. Create a five-number random digits file name and concat with the file extension.

Call "s3" disk in storage and use the put method. Two arguments input method. The first argument for the image path. The second argument for the image object that you received from the client side.

<?php

use Illuminate\Http\Request;
use Storage;
use Str;

public function s3ImageUpload(Request $request)
{
    $path = 'images/';

    $storepath = Storage::disk('s3')->path($path);

    $extension = $request->file('image')->extension();
    
    $imageName = Str::random(5).'.'.$extension;

    Storage::disk('s3')->put($storepath.'/'.$imageName,$request->image);
}

Clear your config and cache, It might happen sometime because of changes in the .env file. Asking for invalid credentials or preventing uploading the file on the s3 bucket.

php artisan config:cache
php artisan config:clear

We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :