Laravel Cloudinary Setup: Seamless Media Upload & Optimization

Managing media in websites can be complex, but Laravel Cloudinary streamlines this process by integrating Laravel with Cloudinary. It simplifies image uploads, transformations, and optimizations, boosting site performance.

In this blog, we’ll help you learn how you can set up Laravel with Cloudinary and how to upload images. Additionally, we’ll also dive into how Laravel development experts used Cloudinary to transform and optimize media files. But first, let’s start with understanding what exactly Laravel Cloudinary is.

What is Laravel Cloudinary?

Laravel Cloudinary is an integration of the Cloudinary service within the Laravel framework. It is designed to streamline media management (images, videos, etc.) on websites. Cloudinary provides a simplified cloud-based solution that simplifies the uploading, storage, and transformation of media files.

It provides a convenient interface for interacting with Cloudinary’s API, allowing you to perform tasks such as:

  • Uploading images and videos: Easily upload media files from your Laravel application to Cloudinary’s cloud storage.
  • Transforming images: Apply various transformations to your images, including resizing, cropping, adding effects, and applying filters.
  • Optimizing images: Automatically optimize your images for web delivery, reducing file size and improving performance.
  • Managing image versions: Create and manage multiple versions of the same image for different use cases.
  • Integrating with other services: Connect Cloudinary with other services like CDN networks for faster content delivery.

By integrating Laravel with Cloudinary, you can enhance the performance of the Laravel site and provide a better user experience. This combination is especially beneficial for applications that rely on visual content, such as eCommerce platforms, blogs, and media sites. Now, let’s start with how professional Laravel developers set up Cloudinary for their projects.

How to Set Up Laravel with Cloudinary?

Setting up Laravel with Cloudinary involves several steps, from installing the necessary packages to configuring your website. Here’s a stepwise process to help you out:

Step 1: Install Laravel (if not already done)

If you haven’t set up a Laravel project yet, you can create one using Composer. Open your terminal and run the following command to create a Laravel project:

composer create-project --prefer-dist laravel/laravel your-project-name

Replace your-project-name with your desired project name. After that, navigate into your project directory using the cd command:

cd your-project-name

Step 2: Install the Cloudinary SDK

To integrate Cloudinary with Laravel, you need to install the Cloudinary PHP SDK. You can do this using Composer:

composer require cloudinary-labs/cloudinary-laravel

This command installs the Laravel-specific package that allows you to use Cloudinary’s features seamlessly within your Laravel site.

Step 3: Create a Cloudinary Account

You need to create a Cloudinary account and obtain your API credentials. So, sign up or log in to your Cloudinary account and then go to the dashboard, where you will find your Cloud Name, API Key, and API Secret.

Step 4: Configure Cloudinary Credentials

Once you have the required credentials, add them to your Laravel project’s configuration. To do so, open the .env file in the root of your Laravel project and add the following lines, replacing your_cloud_name, your_api_key, and your_api_secret with your actual Cloudinary credentials:

CLOUDINARY_URL=cloudinary://your_api_key:your_api_secret@your_cloud_name

If you prefer, you can also set up individual environment variables:

CLOUDINARY_CLOUD_NAME=your_cloud_name
CLOUDINARY_API_KEY=your_api_key
CLOUDINARY_API_SECRET=your_api_secret

Step 5: Set Up the Cloudinary Configuration

If you want to customize the Cloudinary configuration further, you can publish the configuration file. First, create a new configuration file in your config directory:

php artisan vendor:publish --provider="Cloudinary\CloudinaryServiceProvider"

This will create a config/cloudinary.php file where you can adjust the configuration if necessary. With that, the set up is complete. Now, let’s dive jump to how expert Laravel developers upload images to Cloudinary with Laravel.

Need help setting up Cloudinary with Laravel? We’ve got you!

Uploading Images to Cloudinary with Laravel

Uploading images to Cloudinary using Laravel is straightforward, especially when you have the Cloudinary Laravel SDK installed. Below is a step-by-step guide on how to upload images to Cloudinary in a Laravel website.

Step 1: Set Up Cloudinary in Your Laravel Project

Before you can upload images, ensure you have completed the initial setup for Cloudinary as outlined in the previous instructions. This includes installing the Cloudinary package, configuring your credentials in the .env file, and publishing the configuration if needed.

Step 2: Create a Controller for Handling Image Uploads

You need a controller to manage the image upload process. You can create a controller called MediaController (or any name you prefer):

php artisan make:controller MediaController

In app/Http/Controllers/MediaController.php, implement the upload logic:

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Cloudinary\Cloudinary;
class MediaController extends Controller
{
    protected $cloudinary;
    public function __construct()
    {
        $this->cloudinary = new Cloudinary([
            'cloud' => [
                'name' => env('CLOUDINARY_CLOUD_NAME'),
                'api_key' => env('CLOUDINARY_API_KEY'),
                'api_secret' => env('CLOUDINARY_API_SECRET'),
            ],
        ]);
    }
    public function upload(Request $request)
    {
        // Validate the incoming request
        $request->validate([
            'image' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);
        // Handle the image upload
        $imageFile = $request->file('image');
        $uploadedImage = $this->cloudinary->uploadApi()->upload($imageFile->getRealPath());
        // Get the URL of the uploaded image
        $imageUrl = $uploadedImage['secure_url'];
       // Optionally, save the URL to the database or return it in the response
        return response()->json(['url' => $imageUrl]);
    }
}

Step 3: Define Routes for the Upload

Next, define a route for the image upload in your routes/web.php:

use App\Http\Controllers\MediaController;
Route::get('/upload', function () {
    return view('upload');
});
Route::post('/upload', [MediaController::class, 'upload']);

Step 4: Create a File Upload Form

Now, create a Blade view for the upload form. Create a file called upload.blade.php in the resources/views directory:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upload Image to Cloudinary</title>
</head>
<body>
    <h1>Upload Image to Cloudinary</h1>
    <form action="/upload" method="POST" enctype="multipart/form-data">
        @csrf
        <input type="file" name="image" required>
        <button type="submit">Upload</button>
    </form>
    <!-- Display uploaded image if available -->
    @if(session('url'))
        <h2>Uploaded Image:</h2>
        <img src="{{ session('url') }}" alt="Uploaded Image" style="max-width: 300px;">
    @endif
</body>
</html>

Step 5: Handle the Upload and Redirect

In the upload method of your MediaController, you may want to redirect back to the upload form with the uploaded image’s URL stored in the session:

public function upload(Request $request)
{
    // Validate the incoming request
    $request->validate([
        'image' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
    ]);
    // Handle the image upload
    $imageFile = $request->file('image');
    $uploadedImage = $this->cloudinary->uploadApi()->upload($imageFile->getRealPath());
    // Get the URL of the uploaded image
    $imageUrl = $uploadedImage['secure_url'];
    // Redirect back with the image URL
    return redirect()->back()->with('url', $imageUrl);
}

Step 6: Handle the Response in Your View

To display the success message after uploading, you can modify your Blade view as follows:

@if (session('success'))
    <div>{{ session('success') }}</div>
    <img src="{{ session('imageUrl') }}" alt="Uploaded Image" />
@endif

Step 7: Test Your Setup

Start your Laravel project to check whether the website is working or not:

php artisan serve

Visit http://127.0.0.1:8000/upload in your web browser. You should see your file upload form. Select an image and submit the form to upload it to Cloudinary.

Transforming and Optimizing Media on Laravel Cloudinary

To transform and optimize media using Laravel Cloudinary, you can use the capabilities provided by the Cloudinary package for Laravel. Here’s how you can do it:

Step 1: Importing the Cloudinary Facade

To use Cloudinary features in your controller, first, make sure you import the Cloudinary facade at the top of your controller file:

use Cloudinary\Cloudinary;

Step 2: Uploading Media to Cloudinary

When you upload media to Cloudinary, you can apply transformations in the upload method itself. Here’s how to do it:

public function upload(Request $request)
{
    // Validate the incoming request
    $request->validate([
        'image' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
    ]);
    // Handle the image upload
    $uploadedImage = Cloudinary::upload($request->file('image')->getRealPath());
    // Get the public ID of the uploaded image
    $publicId = $uploadedImage->getPublicId();
    return response()->json(['public_id' => $publicId]);
}

Explanation:

  • $request->validate(): Ensures that the file being uploaded is an image and checks for the correct file type and size.
  • Cloudinary::upload(): Handles the image upload using Cloudinary’s API. It uploads the image and stores its public ID.
  • $uploadedImage->getPublicId(): Retrieves the public ID, which can later be used for further transformations or media access.

Step 3: Transform the Uploaded Media

Once the media is uploaded, you can easily create a transformation URL. Below are common transformations you can apply:

Resizing an Image: To resize an image while maintaining the aspect ratio, you can specify the width and height:

$imageUrl = Cloudinary::image($publicId)->resize('300', '300', ['crop' => 'limit']);

Cropping: You can crop an image to specific dimensions:

$imageUrl = Cloudinary::image($publicId)->resize('200', '200', ['crop' => 'fill']);

Changing Format: You can also change the format of an image:

$imageUrl = Cloudinary::image($publicId)->format('png');

These were some of the basic transformations you can do with Laravel Cloudinary. Now let’s see how you can do the same using the URLs.

Step 4: Transforming Media Using URLs

You can also apply transformations when generating URLs to your images or videos. This allows for dynamic transformation on-the-fly based on the requirements of the user’s device or display. Here’s how to generate a URL with transformations:

$publicId = 'your_public_id';
$url = cloudinary_url($publicId, [
    'transformation' => [
        ['width' => 500, 'height' => 500, 'crop' => 'fit'],
        ['quality' => 'auto'],
        ['fetch_format' => 'auto']
    ]
]);

This URL will serve the image optimized for size, quality, and format.

Explanation:

  • cloudinary_url(): Generates the URL with specified transformations.
  • crop: ‘fit’: Ensures the entire image fits within the specified width and height.

URL-based transformations are useful when you need dynamic changes without re-uploading the media.

Step 5: Optimizing Media

Cloudinary automatically optimizes images during the upload process, but you can specify additional optimization options if needed:

Quality Optimization: To apply automatic quality optimization, you can use:

$imageUrl = Cloudinary::image($publicId)->quality('auto');

Responsive Delivery: You can also deliver different image sizes based on the device using responsive transformations:

$imageUrl = Cloudinary::image($publicId)->resize('300', '300')->quality('auto')->format('auto');

Automatic Format and Quality: You can instruct Cloudinary to automatically determine the best format and quality for images:

$imageUrl = cloudinary_url($publicId, [
    'fetch_format' => 'auto', // Automatically chooses the best format
    'quality' => 'auto',      // Automatically sets the quality based on the image
]);

Explanation:

  • fetch_format: auto automatically serves the best image format (e.g., WebP for browsers that support it).
  • quality: auto dynamically adjusts the image quality to balance performance and visual fidelity.

This approach helps ensure your media is delivered in an optimal state, reducing load times while maintaining quality​.

Step 6: Chaining Multiple Transformations

Cloudinary allows you to chain multiple transformations together for a single URL. Here is a example code:

$imageUrl = Cloudinary::image($publicId)
    ->resize('300', '300', ['crop' => 'fill'])
    ->quality('auto')
    ->format('png');

Explanation:

  • resize(‘300’, ‘300’, [‘crop’ => ‘fill’]): Resizes the image to 300×300 pixels with the fill crop mode.
  • format(‘png’): Converts the image to PNG format.
  • quality(‘auto’): Applies automatic quality optimization.

Step 7: Handling Video Transformations (Optional)

For videos, transformations can be applied similarly. Here’s how you can transform and optimize a video:

$videoUrl = Cloudinary::video('your_video_public_id')
    ->resize('640', '360')
    ->quality('auto');

Explanation:

  • Cloudinary::video($publicId): Fetches the video using the public ID.
  • resize(‘640’, ‘360’): Resizes the video to 640×360 pixels.
  • quality(‘auto’): Automatically adjusts the quality of the video based on the viewing device and format.

By utilizing the transformation and optimization, you can enhance media handling, improve load times, and optimize user experience. If you want to build a website with the best practices that ensure performance, consider getting assistance from our Laravel development services.

FAQs About Laravel Cloudinary

What are the benefits of using Cloudinary with Laravel?
There are several benefits of using Cloudinary with Laravel. Here is a list of a few:
  • Automatic media optimization (compression, responsive formats like WebP).
  • Transformation capabilities (resizing, cropping, watermarks).
  • CDN support for fast global delivery.
Is Cloudinary free for Laravel projects?
Cloudinary offers a free tier with limited usage. For high-traffic websites or larger storage needs, you’ll need a paid plan.
Can I apply transformations to images with Laravel Cloudinary?
Yes, Cloudinary allows dynamic transformations like cropping, resizing, and applying filters. These transformations can be applied directly in the image URL or through the API.

Wrapping Up

By integrating Cloudinary with Laravel, you can efficiently handle various types of media on your Laravel site. With Laravel Cloudinary, you can:

  • Apply transformations during upload.
  • Generate optimized URLs dynamically.
  • Work with both images and videos.

These features of Cloudinary make it a preferred choice by developers for optimizing images on the Laravel website. If you are looking to build a robust and well-designed website, hire Laravel developers.

Take your Laravel project to the next level with our expertise!

author
Mayur Upadhyay is a tech professional with expertise in Shopify, WordPress, Drupal, Frameworks, jQuery, and more. With a proven track record in web development and eCommerce development.

Leave a comment