Integrating Cloudflare R2 Storage with Laravel’s S3 Driver

Introduction

In this blog post, we’ll explore how to integrate Cloudflare R2 storage with Laravel’s S3 driver. Cloudflare R2 storage is a scalable, distributed object storage system compatible with the Amazon S3 API, making it a suitable choice for storing and retrieving files in a Laravel application.

Prerequisites

Before proceeding, ensure you have the following:

  1. A Laravel application set up.
  2. Composer installed to manage dependencies.
  3. Cloudflare R2 storage account with API credentials.
  4. AWS SDK for PHP installed via Composer.

Step 1: Install AWS SDK for PHP

First, install the AWS SDK for PHP using Composer by running the following command:

composer require aws/aws-sdk-php

Step 2: Configure the S3 Disk

In Laravel, open the config/filesystems.php file and set up a new disk using the S3 driver for Cloudflare R2 storage:

'disks' => [
    // Other disk configurations...

    'cloudflare_r2' => [
        'driver' => 's3',
        'key' => 'YOUR_CLOUDFLARE_R2_ACCESS_KEY',
        'secret' => 'YOUR_CLOUDFLARE_R2_SECRET_KEY',
        'region' => 'YOUR_CLOUDFLARE_R2_REGION',
        'endpoint' => 'https://YOUR_CLOUDFLARE_R2_ENDPOINT', // e.g., https://r2.example.com
        'bucket' => 'YOUR_CLOUDFLARE_R2_BUCKET_NAME',
    ],
],

Replace 'YOUR_CLOUDFLARE_R2_ACCESS_KEY', 'YOUR_CLOUDFLARE_R2_SECRET_KEY', 'YOUR_CLOUDFLARE_R2_REGION', 'YOUR_CLOUDFLARE_R2_ENDPOINT', and 'YOUR_CLOUDFLARE_R2_BUCKET_NAME' with your Cloudflare R2 storage credentials and endpoint.

Step 3: Using the Cloudflare R2 Disk

You can now utilize the cloudflare_r2 disk in your Laravel application to store and retrieve files:

// Storing a file
Storage::disk('cloudflare_r2')->put('file.txt', 'File contents');

// Retrieving a file
$contents = Storage::disk('cloudflare_r2')->get('file.txt');

// Deleting a file
Storage::disk('cloudflare_r2')->delete('file.txt');

Conclusion

By integrating Cloudflare R2 storage with Laravel’s S3 driver, you can effortlessly manage files in your Laravel application using the familiar filesystem APIs. Cloudflare R2’s compatibility with the S3 API ensures a seamless experience for storing and retrieving files at scale.

Please note that the integration process and Cloudflare R2’s features might evolve over time, so always refer to the official Laravel documentation and Cloudflare R2 documentation for the latest information.

Happy coding with Laravel and Cloudflare R2 storage!


Publié

dans

par

Étiquettes :

Commentaires

Laisser un commentaire