What is s3 bucket?

As an advance developer you might have heard about term s3 bucket and you might be wondering about what it is and how to use it.

S3 bucket is a service provided by amazon where they provide you with a space in the cloud to store assets for your website. For example, if you are creating a movie website where you have lots of images.

You do not want to store them on your web server because you afraid that if something goes wrong all assets will be lost. S3 provides a space in a cloud that you can use to store your website assets they have a good backup utility that you can relay on.

If you don't know how to setup s3 bucket then follow the link below:

Setup S3 Bucket

Add composer dependency for s3 filesystem

Using laravel if you want to use third party php libraries the first step for you to find out if it is possible to install your library through composer.

Composer basically fetch third party library or php based code from remote repository to your local project so that you can use their code.

We have to first install required composer library for our s3 filesystem. Open your terminal window and run following command to install required dependency:

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

This will fetch the remote library and place it inside your vendor folder of laravel project.

I assume that you already already setup your s3 bucket and provided with necessary s3 credentials. Next, we have to open .env file and add following settings.Next, we have to open .env file and add following settings.

AWS_KEY=
AWS_SECRET=
AWS_REGION=
AWS_BUCKET=

Now, open your config/filesystems.php file and update s3 array as below:

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Filesystem Disk
    |--------------------------------------------------------------------------
    |
    | Here you may specify the default filesystem disk that should be used
    | by the framework. The "local" disk, as well as a variety of cloud
    | based disks are available to your application. Just store away!
    |
    */

    'disks' => [

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

    ],

];

We are all set here with setting up s3 bucket configurations. Now, we have to check to see if upload works using our setup.

Let's create a simple upload page for our demo purpose. First of all create a new route which allow use to handle GET and POST request. Open routes/web.php file and add following lines:

Route::get('upload', 'S3Controller@upload')->name('upload');
Route::post('upload', 'S3Controller@upload')->name('upload');    

Once route has been it is a time to setup a controller and a view file. Let's create a new controller called S3Controller using following command:

php artisan make:controller S3Controller

Above command will create a controller file and place it in app/Http/Controllers/S3Controller.php location. Now, open this file and create following method that handles post request.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class S3Controller extends Controller
{
    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($s3filePath, file_get_contents($image), 'public');
        }
       
        return view('upload');
    }
}

Basically, our controller method handles both get and post request here. When a form with image is sent via POST request it gets the image file object.

Then it gets the config from config/filesystems.php file then we create a unique filename by keeping its original filename.

We then define a destination bucket folder for our s3 endpoint so that it will put our uploaded file under assets folder within a s3 bucket.

s3->put function will then upload the file to s3 bucket. You can place this code and wrap it around try and cache if you want to trace any errors that happens during this process.

Finally, create a view file in resources/views/upload.blade.php file with following contents:

<form method="POST" accept-charset="UTF-8" enctype="multipart/form-data">

    <div class="form-group">
        <label for="image">Upload Image to S3 Bucket</label>
        <input id="image" name="image" type="file">
    </div>
    
    <div class="form-group">
        <button type="submit" name="save_btn" class="btn btn-white btn-info btn-bold">
            <i class="ace-icon fa fa-floppy-o bigger-120 blue"></i>
            Save
        </button>
    </div>

    {{ csrf_field() }}

</form>

That is it, now run php artisan serve  command on your terminal and visit http://127.0.0.1:8000/upload. You will see an upload form where you can upload your file and your file then will be uploaded to s3 bucket.

News and Updates

Subscribe to our newsletter and receive the latest news from TheThemeio.


Related Tags


Related Articles