Back to Homepage

Cloudflare Images: Optimize Images on the go

3 min read

Tags:

Cloudflare Images: Optimize Images on the go

Using Cloudflare Images with Laravel involves a combination of Cloudflare's API for image uploads and Laravel's file handling capabilities. Here's a step-by-step guide to uploading images to Cloudflare Images from a Laravel application:

1. Setting up Cloudflare:

  1. API Key: Ensure you have your Cloudflare API key and account email. You will need these to authenticate your requests.

  2. Cloudflare Images: Make sure you've activated the Cloudflare Images service for your account.

2. Laravel Setup:

  1. Install required packages:

    If you're not already using Guzzle (a PHP HTTP client), you'll want to add it to your Laravel project because it makes API interactions smoother

composer require guzzlehttp/guzzle

Configuration:

Add the Cloudflare API credentials to your .env file:

CLOUDFLARE_API_KEY=your_api_key

And reference them in config/services.php:

'cloudflare' => [
    'key' => env('CLOUDFLARE_API_KEY')
],

3. Image Upload:

Here's a basic example of a function that takes a Laravel Request object, extracts an image, and uploads it to Cloudflare:

namespace App\Http\Controllers;

use GuzzleHttp\Client;
use Illuminate\Http\Request;

class ImageController extends Controller
{
    private $client;

    public function __construct(Client $client)
    {
        $this->client = $client;
    }

    public function uploadToCloudflare(Request $request)
    {
        $this->validateImageRequest($request);

        $image = $request->file('image');

        try {
            $data = $this->uploadImageToCloudflare($image);

            // Optionally store the image's URL or other metadata in your database.
            // $data['result']['variants']['original']['url'] provides the direct URL to the uploaded image.

        } catch (\Exception $e) {
            // Handle error, perhaps log it or notify the user.
            return back()->with('error', 'Failed to upload image to Cloudflare.');
        }

        return back()->with('success', 'Image uploaded successfully.');
    }

    private function validateImageRequest(Request $request)
    {
        $request->validate([
            'image' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);
    }

    private function uploadImageToCloudflare($image)
    {
        $response = $this->client->post('https://api.cloudflare.com/client/v4/accounts/:account_id/images/v1', [
            'headers' => [
                'Authorization' => 'Bearer ' . config('services.cloudflare.key'),
            ],
            'multipart' => [
                [
                    'name'     => 'image',
                    'contents' => fopen($image->path(), 'r'),
                    'filename' => $image->getClientOriginalName(),
                ],
            ],
        ]);

        return json_decode($response->getBody(), true);
    }
}

Remember to replace :account_id in the URL with your actual Cloudflare account ID.

4. Frontend:

In your Laravel Blade view, you can have a simple form for image upload:

<form action="{{ route('upload.route') }}" method="post" enctype="multipart/form-data">
    @csrf
    <input type="file" name="image">
    <button type="submit">Upload</button>
</form>

Conclusion:

This is a basic overview of how you can upload images to Cloudflare Images using Laravel. You might want to add more advanced features like image validation, error handling, and storing image metadata in your database. As always, remember to handle user data responsibly and securely.

Follow @LaravelSage on X → Follow @LaravelSage on Facebook →
Aniket Singh

Aniket Singh

View All Articles

Full-stack developer with a knack for Merging creativity with technical expertise for standout solutions.

Related Articles

data_forget Helper for Laravel

data_forget Helper for Laravel

Since Laravel version 10.15, there is a new utility function called data_forget that allows you to remove keys from an array or object using a "dot" notation.

Laravel Tenant Application with Tenancy

Laravel Tenant Application with Tenancy

You can make your Laravel app multi-tenant using the Tenancy for Laravel Tenant package. This tenancy package lets you make any Laravel application multi-tenant without rewriting it.

Top Laravel Packages for Building Powerful Applications

Top Laravel Packages for Building Powerful Applications

Are you ready to take your Laravel skills to the next level and build extraordinary applications? Look no further! In this blog post, we will unveil a treasure trove of top packages that will revolutionize your development process.

Subscribe for 20+ new Laravel tutorials every week

You can unsubscribe at any time. You'll also get -20% off my courses!

© 2024

 

Laravel Sage

   |    Privacy Policy