Hello Artisan,
In this Laravel amazon s3 file upload tutorial, I will discuss how to upload files to amazon s3 web services in the Laravel application. Did you know that Amazon web service S3 bucket is a service provided by Amazon where they provide space in the cloud to store files for your website?
For example, let assume we are going to create a Large scale application and there are many images needed to store. So now we have a massive data file that has to store on our server. But we do not want to store them on your web server because you are afraid that if something goes wrong all files will be lost.
To solve this problem for you, S3 provides a space in a cloud that you can use to store your website files they have a good backup utility that you can rely on. Let's see how to upload files in amazon web services s3 cloud in Laravel. We need this league/flysystem-aws-s3-v3
package to upload files on amazon s3 in the Laravel application.
So we have to install the required composer library for our S3 Filesystem
composer require league/flysystem-aws-s3-v3
Next, we have to open .env file and add the following settings. Next, we have to open .env file and add the following settings.
.env
AWS_KEY=
AWS_SECRET=
AWS_REGION=
AWS_BUCKET=
Now, open your filesystems.php
file and update the s3 array as below:
config/filesystems.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'),
],
],
];
Now we have to create a route to store our files on amazon s3 in laravel. So create a route:
Route::post('upload', 'S3Controller@upload')->name('upload');
Now update your controller like below to store files video or any image to your s3 storage using laravel application.
App\Http\Controllers\S3Controller.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class S3Controller extends Controller
{
public function upload(Request $request)
{
if( $request->has('image') )
{
$image = $request->file('image');
$s3 = \Storage::disk('s3');
$file_name = uniqid() .'.'. $image->getClientOriginalExtension();
$s3filePath = '/assets/' . $file_name;
$s3->put($s3filePath, file_get_contents($image), 'public');
}
return view('upload');
}
}
Read also: Configure Your Laravel Queues with AWS SQS
Hope it can help you.
#laravel #laravel-8x #image-upload