PHP code example of bardan-io / temp-media-for-laravel

1. Go to this page and download the library: Download bardan-io/temp-media-for-laravel library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

bardan-io / temp-media-for-laravel example snippets


// 1. Upload images individually
$uploadResponse = app(TempMediaServiceInterface::class)->uploadTempMedia(
    $uploadedFile,
    session()->getId(),
    auth()->id()
);

// 2. Create a product with temp media IDs
$product = Product::create([
    'name' => 'My Product',
    'description' => 'Product description',
    // ... other fields
]);

// 3. Transfer temp media to product
$transferResult = $product->transferTempMedia(['temp-media-uuid-1', 'temp-media-uuid-2']);

use BardanIO\TempMedia\Traits\HandlesTempMedia;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;

class Product extends Model implements HasMedia
{
    use InteractsWithMedia;
    use HandlesTempMedia;

    // Transfer temp media to default collection
    public function attachTempImages(array $tempMediaIds)
    {
        return $this->transferTempMedia($tempMediaIds, 'product_images');
    }
}

return [
    // TTL for temporary files (hours)
    'default_ttl_hours' => 24,
    
    // Maximum file size in bytes
    'max_file_size' => 10 * 1024 * 1024, // 10MB
    
    // Allowed MIME types
    'allowed_mime_types' => [
        'image/jpeg',
        'image/png',
        'image/webp',
        'image/gif',
    ],
    
    // Storage disk
    'disk' => 'public',
    
    // Enable automatic cleanup
    'enable_auto_cleanup' => true,
    
    // Route configuration
    'routes' => [
        'prefix' => 'api/temp-media',
        'middleware' => ['api'],
    ],
    
    // Rate limiting
    'rate_limiting' => [
        'enabled' => true,
        'max_attempts' => 60,
        'decay_minutes' => 1,
    ],
];

// Listen for uploads
Event::listen(TempMediaUploaded::class, function ($event) {
    Log::info('Temp media uploaded', [
        'id' => $event->tempMedia->id,
        'user' => $event->uploadDto->userId,
    ]);
});

// Listen for transfers
Event::listen(MediaTransferred::class, function ($event) {
    Log::info('Media transferred', [
        'model' => get_class($event->targetModel),
        'count' => $event->transferDto->transferredCount,
    ]);
});
bash
php artisan vendor:publish --tag="temp-media-migrations"
php artisan migrate
bash
php artisan vendor:publish --tag="temp-media-config"