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

Azure Storage Laravel Package

microsoft/azure-storage

Deprecated PHP client libraries for Microsoft Azure Storage (Blob, Table, Queue, File). Provides APIs to create/list/delete containers, blobs, tables, entities, queues, and metadata. In community support until 17 Mar 2024, then retired.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup for Laravel Integration
1. **Install via Composer** (in `composer.json`):
   ```json
   "require": {
       "microsoft/azure-storage-blob": "^1.5.4",
       "microsoft/azure-storage-table": "^1.1.6",
       "microsoft/azure-storage-queue": "^1.3.4",
       "microsoft/azure-storage-file": "^1.2.5"
   }

Run composer install.

  1. Publish Configuration (optional but recommended): Create a config file for Azure credentials:

    php artisan vendor:publish --provider="MicrosoftAzure\Storage\Common\StorageSettings" --tag=config
    

    Update config/azure-storage.php with your connection string:

    return [
        'connection_string' => env('AZURE_STORAGE_CONNECTION_STRING'),
        'default_service' => 'blob', // blob|table|queue|file
    ];
    
  2. First Use Case: Upload a Blob

    use MicrosoftAzure\Storage\Blob\BlobRestProxy;
    use MicrosoftAzure\Storage\Common\ServiceException;
    
    $connectionString = config('azure-storage.connection_string');
    $blobClient = BlobRestProxy::createBlobService($connectionString);
    
    try {
        $blobName = 'test-blob-' . time() . '.txt';
        $blobClient->createBlockBlob('my-container', $blobName, fopen('test.txt', 'r'));
        Log::info("Blob uploaded successfully: $blobName");
    } catch (ServiceException $e) {
        Log::error("Blob upload failed: " . $e->getMessage());
    }
    

Implementation Patterns

1. Service Initialization

  • Singleton Pattern for Clients: Create a Laravel service provider to initialize clients once:

    // app/Providers/AzureStorageServiceProvider.php
    public function register()
    {
        $this->app->singleton('azure.blob', function ($app) {
            return BlobRestProxy::createBlobService(config('azure-storage.connection_string'));
        });
        // Repeat for table, queue, file services
    }
    

    Bind in config/app.php:

    'azure' => [
        'blob' => env('AZURE_BLOB_SERVICE', 'azure.blob'),
        'table' => env('AZURE_TABLE_SERVICE', 'azure.table'),
    ],
    
  • Dynamic Service Selection: Use a facade or helper to switch services dynamically:

    // app/Helpers/AzureHelper.php
    public static function getService($type = 'blob')
    {
        return app("azure.$type");
    }
    

2. Common Workflows

Blob Operations

  • Upload/Download with Streams:

    // Upload from Laravel storage
    $stream = Storage::disk('local')->readStream('file.pdf');
    $blobClient->createBlockBlob('container', 'remote-file.pdf', $stream);
    
    // Download to Laravel storage
    $blob = $blobClient->getBlob('container', 'remote-file.pdf');
    Storage::disk('local')->put('downloaded-file.pdf', $blob->getContent());
    
  • Batch Operations: Use ListBlobOptions for pagination:

    $blobs = [];
    $listBlobsOptions = new ListBlobOptions();
    $listBlobsOptions->setPrefix('prefix/');
    $blobList = $blobClient->listBlobs('container', $listBlobsOptions);
    foreach ($blobList as $blob) {
        $blobs[] = $blob->getName();
    }
    

Table Operations

  • Entity CRUD with Laravel Eloquent: Map Azure Table entities to Eloquent models:
    // app/Models/AzureUser.php
    class AzureUser extends Model implements ITableEntity
    {
        use Notifiable;
        public $partitionKey;
        public $rowKey;
        public $timestamp;
        public $etag;
    }
    
    Use a repository pattern:
    // app/Repositories/AzureTableRepository.php
    public function saveEntity($entity)
    {
        $tableClient = TableRestProxy::createTableService(config('azure-storage.connection_string'));
        $tableClient->insertOrReplaceEntity('Users', $entity);
    }
    

Queue Operations

  • Job Processing with Laravel Queues: Integrate with Laravel's queue system:
    // app/Providers/QueueServiceProvider.php
    public function boot()
    {
        Queue::extend('azure', function ($app) {
            return new AzureQueueConnection(
                Queue::connection('azure')->getQueue(),
                config('azure-storage.connection_string')
            );
        });
    }
    
    Push jobs to Azure Queue:
    Queue::connection('azure')->push('process-order', $orderData);
    

File Operations

  • Shared Access Signatures (SAS): Generate SAS tokens for secure access:
    $sasToken = $fileClient->createSharedAccessSignature(
        'share',
        'directory/file.txt',
        new SharedAccessSignaturePermissions('r'),
        new SharedAccessExpiryTime('2023-12-31T23:59:59Z')
    );
    $url = $fileClient->getFileServiceProperties()->getPrimaryEndpoint() .
           '/share/directory/file.txt?' . $sasToken;
    

3. Middleware Integration

  • Logging Middleware: Log all Azure Storage requests/responses:

    $logMiddleware = new class implements IMiddleware {
        public function handle($request, $handler) {
            Log::debug('Azure Request: ' . $request->getUri());
            $response = $handler->handle($request);
            Log::debug('Azure Response: ' . $response->getStatusCode());
            return $response;
        }
    };
    $options = ['middlewares' => [$logMiddleware]];
    $blobClient = BlobRestProxy::createBlobService($connectionString, $options);
    
  • Retry Middleware: Enable retries for transient failures:

    $retryMiddleware = RetryMiddlewareFactory::create(
        RetryMiddlewareFactory::GENERAL_RETRY_TYPE,
        3,
        1000,
        RetryMiddlewareFactory::EXPONENTIAL_INTERVAL_ACCUMULATION
    );
    $blobClient->pushMiddleware($retryMiddleware);
    

4. Event Handling

  • Listen for Blob Events: Use Laravel events to trigger actions on blob uploads:
    // app/Listeners/HandleBlobUpload.php
    public function handle(BlobUploaded $event)
    {
        // Process uploaded blob (e.g., generate thumbnail)
    }
    
    Dispatch events manually or use a queue job to poll for new blobs.

Gotchas and Tips

1. Connection and Authentication

  • Connection String Security:

    • Never hardcode connection strings. Use Laravel's .env:
      AZURE_STORAGE_CONNECTION_STRING=DefaultEndpointsProtocol=https;AccountName=...;AccountKey=...;EndpointSuffix=core.windows.net
      
    • Restrict access to the .env file in production.
  • AAD Authentication: For Azure Active Directory authentication, use the token credential method:

    $token = 'your-access-token';
    $blobClient = BlobRestProxy::createBlobServiceWithTokenCredential(
        $token,
        'DefaultEndpointsProtocol=https;AccountName=...;EndpointSuffix=core.windows.net'
    );
    

2. Performance and Scalability

  • Large File Handling:

    • Use createPageBlob for files > 512MB or when random writes are needed.
    • For block blobs, use createBlockBlob with setBlobContentMD5 for integrity checks:
      $blobClient->createBlockBlob(
          'container',
          'large-file.zip',
          fopen('large-file.zip', 'r'),
          null,
          null,
          ['blobContentMD5' => md5_file('large-file.zip')]
      );
      
  • Batch Operations:

    • Azure Table batch operations are limited to 100 entities. Use TableBatch:
      $batch = new TableBatch();
      foreach ($entities as $entity) {
          $batch->insertEntity($entity);
      }
      $tableClient->submitTableBatch('table-name', $batch);
      

3. Debugging and Error Handling

  • Common Exceptions:

    • ServiceException: Wrap in try-catch blocks. Check $e->getCode() for HTTP status codes.
    • 404 Not Found: Verify container/table/share names and permissions.
    • 403 Forbidden: Ensure the connection string or SAS token has correct permissions.
  • Logging: Enable Guzzle logging for HTTP details:

    $options = [
        'http' => [
            'debug' => fopen('azure-debug.log', 'w'),
            'verify' => false, // Only for testing; use cacert.pem in production
        ]
    ];
    
  • SSL/TLS Issues:

    • If you encounter `Unable to get local
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.
datacore/hub-sdk
alengo/sulu-http-cache-bundle
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php
agtp/mod-php
centraldesktop/protobuf-php
trappistes/laravel-custom-fields
splash/sonata-admin
splash/metadata