Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Cloudinary Laravel Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require cloudinary-labs/cloudinary-laravel
    

    Publish the config file:

    php artisan vendor:publish --provider="CloudinaryLabs\CloudinaryLaravel\CloudinaryServiceProvider" --tag="config"
    
  2. 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.

  3. First Use Case: Upload an image from a request:

    use CloudinaryLabs\CloudinaryLaravel\Facades\Cloudinary;
    
    $result = Cloudinary::upload(request()->file('image'));
    $url = $result->getSecureUrl();
    

Implementation Patterns

Common Workflows

  1. 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']
    ]);
    
  2. 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']
    ]);
    
  3. Deleting Assets:

    Cloudinary::delete('public_id');
    Cloudinary::delete(['public_id_1', 'public_id_2']);
    
  4. 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();
    }
    
  5. Batch Operations:

    // Upload multiple files
    $results = Cloudinary::uploadMultiple($filesCollection);
    
    // Generate URLs for multiple assets
    $urls = collect($publicIds)->map(fn($id) => Cloudinary::url($id));
    

Best Practices

  • Use Queues for Heavy Uploads: Offload large uploads to a queue to avoid timeouts.
  • Leverage Transformations: Define reusable transformations in the config to avoid repetition.
  • Cache URLs: Cache generated URLs in Redis or the file system if they don’t change often.
  • Fallbacks: Implement fallback logic for when Cloudinary is unavailable (e.g., local storage).

Gotchas and Tips

Pitfalls

  1. Configuration Overrides:

    • The package respects .env variables but can be overridden in config/cloudinary.php. Ensure consistency between the two.
    • Example: If CLOUDINARY_API_KEY is set in .env but cloud_name is only in the config, the latter will take precedence.
  2. Public ID Conflicts:

    • Reusing the same public_id for uploads will overwrite the asset. Use unique IDs (e.g., UUIDs) or append timestamps.
    • Example:
      $publicId = 'user_' . auth()->id() . '_' . time() . '_' . $file->getClientOriginalName();
      
  3. Transformation Syntax:

    • Cloudinary’s transformation syntax is strict. Use the official documentation to validate syntax.
    • Example of a common mistake:
      // Incorrect: Missing array wrapper
      Cloudinary::url('public_id', 'width=100,height=100');
      
      // Correct:
      Cloudinary::url('public_id', ['width' => 100, 'height' => 100]);
      
  4. File Size Limits:

    • Cloudinary has a file size limit (2GB for authenticated uploads). Validate files on the client or server side before upload.
    • Example:
      if (request()->file('image')->getSize() > 2000000000) { // 2GB
          throw new \Exception('File too large');
      }
      
  5. Async Uploads:

    • The 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');
      

Debugging Tips

  1. Enable Logging: Add this to config/cloudinary.php to debug issues:

    'debug' => env('CLOUDINARY_DEBUG', false),
    

    Logs will appear in storage/logs/laravel.log.

  2. Validate Credentials: Test your credentials manually using the Cloudinary Console or the API.

  3. Check Response: Inspect the response object for errors:

    $result = Cloudinary::upload($file);
    if ($result->isError()) {
        \Log::error('Cloudinary upload error:', ['error' => $result->getErrorMessage()]);
    }
    

Extension Points

  1. Custom Storage Adapter: Extend the package to support custom storage backends by implementing the CloudinaryLabs\CloudinaryLaravel\Contracts\CloudinaryStorage interface.

  2. 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);
    }
    
  3. Events: Listen for upload events to trigger additional actions (e.g., notifications, analytics):

    Cloudinary::upload($file)->then(function ($result) {
        event(new ImageUploaded($result->getPublicId()));
    });
    
  4. 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);
    });
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky