cloudinary-labs/cloudinary-laravel
Laravel integration for Cloudinary: upload, manage, and transform images and videos with an easy Facade/API, configurable storage, and URL generation. Supports signed delivery, eager transformations, and seamless use in apps and queues.
Installation:
composer require cloudinary-labs/cloudinary-laravel
Publish the config file:
php artisan vendor:publish --provider="CloudinaryLabs\CloudinaryLaravel\CloudinaryServiceProvider" --tag="config"
Configuration:
Add your Cloudinary credentials to .env:
CLOUDINARY_CLOUD_NAME=your_cloud_name
CLOUDINARY_API_KEY=your_api_key
CLOUDINARY_API_SECRET=your_api_secret
Optionally, set a default transformation or folder in config/cloudinary.php.
First Use Case: Upload an image from a request:
use CloudinaryLabs\CloudinaryLaravel\Facades\Cloudinary;
$result = Cloudinary::upload(request()->file('image'));
$url = $result->getSecureUrl();
Uploading Files:
// Basic upload
$uploadResult = Cloudinary::upload($file);
// With custom options
$uploadResult = Cloudinary::upload($file, [
'folder' => 'user_uploads',
'public_id' => 'custom_id',
'transformation' => ['width' => 500, 'height' => 500, 'crop' => 'limit']
]);
Generating URLs:
// Direct URL generation
$url = Cloudinary::url('public_id', [
'transformation' => ['width' => 300, 'height' => 200, 'crop' => 'fill']
]);
// Dynamic URL generation (e.g., for responsive images)
$url = Cloudinary::url('public_id', [
'transformation' => ['width' => 'auto', 'height' => 300, 'crop' => 'scale']
]);
Deleting Assets:
Cloudinary::delete('public_id');
Cloudinary::delete(['public_id_1', 'public_id_2']);
Integration with Eloquent:
// Accessor for model
public function getImageUrlAttribute()
{
return Cloudinary::url($this->image_public_id, [
'transformation' => ['width' => 200, 'height' => 200]
]);
}
// Mutator for upload
public function setImageAttribute($file)
{
$this->image_public_id = Cloudinary::upload($file)->getPublicId();
}
Batch Operations:
// Upload multiple files
$results = Cloudinary::uploadMultiple($filesCollection);
// Generate URLs for multiple assets
$urls = collect($publicIds)->map(fn($id) => Cloudinary::url($id));
Configuration Overrides:
.env variables but can be overridden in config/cloudinary.php. Ensure consistency between the two.CLOUDINARY_API_KEY is set in .env but cloud_name is only in the config, the latter will take precedence.Public ID Conflicts:
public_id for uploads will overwrite the asset. Use unique IDs (e.g., UUIDs) or append timestamps.$publicId = 'user_' . auth()->id() . '_' . time() . '_' . $file->getClientOriginalName();
Transformation Syntax:
// Incorrect: Missing array wrapper
Cloudinary::url('public_id', 'width=100,height=100');
// Correct:
Cloudinary::url('public_id', ['width' => 100, 'height' => 100]);
File Size Limits:
if (request()->file('image')->getSize() > 2000000000) { // 2GB
throw new \Exception('File too large');
}
Async Uploads:
upload method is synchronous by default. For large files, use the uploadAsync method (if available) or queue the upload:
UploadImageJob::dispatch($file, $options)->onQueue('cloudinary');
Enable Logging:
Add this to config/cloudinary.php to debug issues:
'debug' => env('CLOUDINARY_DEBUG', false),
Logs will appear in storage/logs/laravel.log.
Validate Credentials: Test your credentials manually using the Cloudinary Console or the API.
Check Response: Inspect the response object for errors:
$result = Cloudinary::upload($file);
if ($result->isError()) {
\Log::error('Cloudinary upload error:', ['error' => $result->getErrorMessage()]);
}
Custom Storage Adapter:
Extend the package to support custom storage backends by implementing the CloudinaryLabs\CloudinaryLaravel\Contracts\CloudinaryStorage interface.
Middleware for Transformations: Create middleware to apply default transformations to all URLs:
public function handle($request, Closure $next)
{
$request->merge([
'cloudinary_transformation' => ['width' => 800, 'height' => 600, 'crop' => 'limit']
]);
return $next($request);
}
Events: Listen for upload events to trigger additional actions (e.g., notifications, analytics):
Cloudinary::upload($file)->then(function ($result) {
event(new ImageUploaded($result->getPublicId()));
});
Testing:
Use the CloudinaryFake class for testing:
use CloudinaryLabs\CloudinaryLaravel\Facades\Cloudinary;
use CloudinaryLabs\CloudinaryLaravel\Testing\CloudinaryFake;
beforeEach(function () {
CloudinaryFake::fake();
});
afterEach(function () {
CloudinaryFake::assertUploaded(1);
});
How can I help you explore Laravel packages today?