Table of Contents
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 to set up Laravel with Cloudinary and how to upload images. Additionally, we’ll also dive into how to use 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 for 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 CDN networks for faster content delivery.
| Laravel app’s performance and provide a better user experience. |
| By integrating Laravel with Cloudinary, you can optimize the Laravel app’s performance and provide a better user experience, similar to how Laravel Scout enhances search performance through full-text indexing. |
This combination is especially beneficial for applications that rely on visual content, such as e-commerce platforms, blogs, and media sites.
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 lets you use Cloudinary’s features seamlessly on your Laravel site.
Step 3: Create a Cloudinary Account
You need to create a Cloudinary account and obtain your API credentials. So, sign in to your Cloudinary account, then go to the dashboard to 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 setup is complete. Now, let’s dive right into how expert Laravel developers upload images to Cloudinary with Laravel.
Uploading Images to Cloudinary with Laravel
Uploading images to Cloudinary using Laravel is straightforward, especially when you have the Cloudinary Laravel SDK installed. For developers looking to integrate AI-driven automation in media workflows, Laravel OpenAI offers seamless ways to generate and manage dynamic content intelligently.
Below is a step-by-step guide to uploading images to Cloudinary on 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. Additionally, you can store these optimized media records in Laravel with MongoDB to handle large-scale, unstructured image metadata efficiently.
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 uploaded file is an image and checks its 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: automatically adjusts 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 lets you chain multiple transformations into a single URL. Here is an 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 video quality based on the viewing device and format.
By leveraging transformations and optimizations, you can enhance media handling, improve load times, and enhance the user experience. If you want to build a website that follows best practices to ensure performance, consider our Laravel development services.
Wrapping Up
By integrating Cloudinary with Laravel, you can efficiently handle various types of media on your Laravel site. You can hire Laravel developers to help you with the integration. 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 for developers looking to optimize images on Laravel websites.
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.
How can I generate screenshots or PDFs of Cloudinary-hosted media within Laravel?
You can use Browsershot Laravel to capture screenshots or convert Laravel views and media outputs into high-quality PDFs automatically.
How can I make my Cloudinary media library searchable and scalable?
By implementing Laravel Elasticsearch, you can build advanced indexing and search capabilities for your Cloudinary-stored assets and other site data.
Build Powerful Laravel Applications
Learn how to leverage Laravel's powerful features for efficient and scalable web development.


