Laravel 5.x Store Uploaded Files to Amazon S3

Recently in one of my Laravel 5.2 project, we used Amazon s3 to store static files and user uploaded files. So here in this blog I am going to explain how to do this.

1) First of all install following plugin through composer.

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

2) Now add your S3 credentials to your environment (.env file)

S3_KEY=YOUR_KEY
S3_SECRET=YOUR_SECRET
S3_REGION=YOUR_REGION
S3_BUCKET=YOUR_BUCKET

3) Open config.filesystems.php and configure s3 driver as follow.

‘s3’ => [
            ‘driver’ => ‘s3’,
            ‘key’    => env(‘S3_KEY’),
            ‘secret’ => env(‘S3_SECRET’),
            ‘region’ => env(‘S3_REGION’),y.
            ‘bucket’ => env(‘S3_BUCKET’),
        ]

4) Now open controller where you have code to manage uploaded file and add following dependency.

use IlluminateContractsFilesystemFilesystem;

5) Use following code to store your file to S3.

$image = $request->file(‘user_uploaded_image’);
$imageFileName = time() . ‘.’ . $image->getClientOriginalExtension();
$s3 = Storage::disk(‘s3’);

$filePath = ‘/mypath’/.$imageFileName;
$s3->put($filePath, file_get_contents($image), ‘public’);
$uploadedFileS3Path = ‘https://’.env(‘S3_BUCKET’).’/’.$filePath;
Please note in my case I configured S3 bucket to be direct URL of uploaded file. In case your case if you have not configured it then your path will be as follow.
$uploadedFileS3Path = ‘http://s3-‘.env(‘S3_REGION’).’.amazonaws.com/’.env(‘S3_BUCKET’).’/’.$filePath;
This path you can use to display file and you can store it to database as well.
Special Case 
If you are using it in localhost using XAMPP in your windows system. You have to do following few steps.
Download certificate pem file from this link. https://curl.haxx.se/ca/cacert.pem and store it to some where in your C drive or whatever drive you have your xampp installed.
For example I put it in  C:codecacert.pem
Now open your php.ini file and bottom of the file add following line.
curl.cainfo = C:codecacert.pem
That’s it and it will work in your local environment too. Hope this helps you.
This entry was posted in Amazon, Amazon AWS, Amazon S3, Laravel, Laravel 5.2, PHP, PHP Extensions, PHP Framework on by .

About Hiren Dave

Hiren Dave is a software engineer, blogger and consultant with over 9 years of professional experience. He writes code in number of languages. Hiren has a passion for developing web apps, mobile apps and writing books and blog articles about programming. He has a solid experience of startups as he manages products for few startups. He is also passionate about researching and learning new technologies and trends. He has also authored a book Instant Sencha Touch, published by Packt and creator of Video Course "Beginning Laravel" for Packt

Leave a Reply

Your email address will not be published. Required fields are marked *