Using the Object storage service with PHP Laravel filesystems for S3.
The default laravel S3 configuration does not allow us to set the endpoint option which is required since we are not actually using AWS S3 but the NodeChef object storage service which is S3 compatible.
To configure for Laravel, follow the below steps.
-
1. Set the neccessary variables in your .env file
OSS_KEY=enter_your_access_key
OSS_SECRET=enter_your_secret_key
OSS_REGION=us-east-1
OSS_ENDPOINT=https://oss.nodechef.com
OSS_BUCKET_NAME=webPics
- 2. Configure your config/filesystems.php file with the below information
's3' => [
'driver' => 's3',
'key' => env('OSS_KEY'),
'secret' => env('OSS_SECRET'),
'region' => env('OSS_REGION'),
'version' => 'latest',
'endpoint' => env('OSS_ENDPOINT'),
'bucket_name' => env('OSS_BUCKET_NAME')
]
The above example, assumes you have configured your .env file with the above variables.
-
3. Create a custom service provider by using the Storage facade's extend method to define the custom drive
use Illuminate\Support\ServiceProvider;
use Aws\S3\S3Client;
use League\Flysystem\AwsS3v3\AwsS3Adapter;
use League\Flysystem\Filesystem;
use Aws\Laravel\AwsServiceProvider;
use Storage;
class AwsS3ServiceProvider extends ServiceProvider
{
/**
* Perform post-registration booting of services.
*
* @return void
*/
public function boot()
{
Storage::extend('s3', function($app, $config) {
$client = new S3Client([
'credentials' => [
'key' => $config['key'],
'secret' => $config['secret'],
],
'region' => $config['region'],
'version' => $config['version'],
'endpoint' => $config['endpoint']
]);
return new Filesystem(new AwsS3Adapter($client, $config['bucket_name']));
});
}
/**
* Register bindings in the container.
*
* @return void
*/
public function register()
{
//
}
}
-
4. Simple example to upload the file in the request to the NodeChef S3 compatible bucket
use Illuminate\Http\Request;
use Illuminate\Contracts\Filesystem\Filesystem;
public function uploadFileToS3(Request $request)
{
$image = $request->file('image');
$imageFileName = time() . $image->getClientOriginalName();
$s3 = \Storage::disk('s3');
$s3->put($imageFileName, file_get_contents($image), 'public');
$publicURI = 'https://webPics.oss.nodechef.com/' . $imageFileName;
}
Note, in the above example we declare an unused variable $publicURI. This is only for demonstration purposes, to guide you on how to create
the public url of the files you upload.