Laravel Uplod Images to s3 Bucket

Nov 29, 2017 Laravel Framework PHP
How to upload images to s3 | learn2torials

What is s3 bucket?

S3 bucket is a space in cloud provided by AWS. Rather then storing assets to your web server it is convenient to store them on s3 bucket. It is not a good practise to store assets on the same web server because if something happens to your web server you will loose them.

Upload Files to AWS S3 using Laravel

Storing your assets to s3 and serving them through cdn will be more quicker way to display them on your site. Laravel 5 makes it easy to handle communication between your server and s3 bucket.

Let's take a look at the configuration file located in config/filesystems.php:

    'disks' => [
        's3' => [
            'driver' => 's3',
            'key' => env('AWS_KEY'),
            'secret' => env('AWS_SECRET'),
            'region' => env('AWS_REGION'),
            'bucket' => env('AWS_BUCKET'),
        ]
    ],

Next, step is to make sure you have following dependency added to your composer:

composer require league/flysystem-aws-s3-v2 ~1.0

Login to your aws account and get these credentials. Once you have them you can set this variables in .env file as shown below:

AWS_KEY=
AWS_SECRET=
AWS_REGION=
AWS_BUCKET=

Let's assume that you have a web page where you have a file input with upload button. Once user clicks on upload button your laravel application calls your controller to handle post request with image object.

Let's handle this request add following code to your controller file:

public function upload(Request $request)
{
       if( $request->isMethod('post') )
      {
             # get file from request object
             $image = $request->file('image');

             # get s3 object make sure your key matches with
             # config/filesystem.php file configuration
             $s3 = \Storage::disk('s3');

             # rename file name to random name
             $file_name = uniqid() .'.'. $image->getClientOriginalExtension();

             # define s3 target directory to upload file to
             $s3filePath = '/assets/' . $file_name;

             # finally upload your file to s3 bucket
             $s3->put($filePath, file_get_contents($image), 'public');
      }
}

That is it, once file is uploaded to s3 bucket you can manually go and check your bucket to see if file upload is successful. Make sure you handle error caching properly in your real application.

Rate This Article

Tutorials about how to upload image to s3 bucket using composer library

4.90

About Author