PHP code example of okamal / laravel-media-zone

1. Go to this page and download the library: Download okamal/laravel-media-zone 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/ */

    

okamal / laravel-media-zone example snippets




namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use OKamal\LaravelMediaZone\Traits\HasMediaZones;

class Post extends Model
{
    use HasMediaZones;
    
    protected $fillable = ['title', 'content'];
}



namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
    public function store(Request $request)
    {
        $request->validate([
            'title' => 'e'));
        
        // Sync media to model
        $post->syncMedia([
            'featured_image' => [$request->featured_image],
            'gallery' => $request->gallery ?? []
        ]);
        
        return redirect()->route('posts.index')
            ->with('success', 'Post created successfully!');
    }
}

use Illuminate\Database\Eloquent\Casts\Attribute;

protected function featuredImage(): Attribute
{
    return Attribute::make(
        get: fn() => $this->getFirstMediaByZone('featured_image'),
    );
}

protected function gallery(): Attribute
{
    return Attribute::make(
        get: fn() => $this->getMediaByZone('gallery'),
    );
}

return [
    // Storage disk (must be configured in config/filesystems.php)
    'disk' => env('MEDIA_ZONE_DISK', 'public'),

    // Base path for media files
    'base_path' => env('MEDIA_ZONE_BASE_PATH', 'media'),

    // Temporary upload path
    'temp_path' => env('MEDIA_ZONE_TEMP_PATH', 'media/temp'),

    // Global validation defaults
    'validation' => [
        'max_file_size' => 10240, // KB (10MB)
        'allowed_mime_types' => [
            'image/jpeg',
            'image/png',
            'image/gif',
            'image/webp',
            'image/svg+xml',
            'application/pdf',
            'application/msword',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            'application/vnd.ms-excel',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'video/mp4',
            'video/mpeg',
        ],
    ],

    // Auto-delete physical files when media records are deleted
    'auto_delete_files' => true,

    // Cleanup old temporary files
    'cleanup_temp_files' => [
        'enabled' => true,
        'older_than_hours' => 24,
    ],

    // Routes configuration
    'routes' => [
        'enabled' => true,
        'prefix' => 'api/media-zone',
        'middleware' => ['web', 'auth'],
        'name' => 'media-zone.',
    ],

    // Per-model validation configurations
    'models' => [
        // Example:
        // App\Models\Post::class => App\MediaZone\PostMediaConfig::class,
    ],
];

// Get all media for this model
$model->media; // Collection

// Get media by zone
$model->getMediaByZone('gallery'); // Collection

// Get first media in zone
$model->getFirstMediaByZone('avatar'); // Media|null

// Get media URL (helper)
$model->getMediaUrl('avatar'); // string|null

// Sync media (recommended for form submissions)
$post->syncMedia([
    'featured_image' => [$imageId],
    'gallery' => [$id1, $id2, $id3],
    'documents' => [$docId]
]);

// Add single media to zone
$post->addMediaToZone($mediaId, 'avatar');

// Replace all media in a zone
$post->replaceMediaInZone([$newId1, $newId2], 'gallery');

// Check if model has media in a zone
if ($post->hasMediaInZone('featured_image')) {
    // Has featured image
}

// Clear specific zone
$post->clearMediaZone('gallery');

// Delete all media for this model
$post->deleteMedia();

// Get storage directory for a zone
$path = $post->mediaStorageDirectory('gallery');
// Example output: "media/posts/galleries"

$media = $post->featured_image;

$media->id;          // int
$media->name;        // string - Filename
$media->url;         // string - Public URL
$media->mime_type;   // string - MIME type
$media->size;        // int - Size in bytes
$media->human_size;  // string - Formatted size (e.g., "2.5 MB")
$media->zone;        // string - Zone name
$media->storage_path; // string - Disk path

// Type checks
$media->isImage();    // bool
$media->isVideo();    // bool
$media->isDocument(); // bool



namespace App\MediaZone;

use OKamal\LaravelMediaZone\Contracts\MediaZoneConfig;

class PostMediaConfig implements MediaZoneConfig
{
    public function rules(string $zone): array
    {
        return match ($zone) {
            'featured_image' => [
                'featured_image' => [
                    '  'image',
                    'max:2048', // 2MB
                    'mimes:jpeg,png',
                ],
            ],
            'attachments' => [
                'attachments' => [
                    ' => 'Featured image must not exceed 5MB.',
            ],
            'gallery' => [
                'gallery.max' => 'Each gallery image must not exceed 2MB.',
            ],
            default => [],
        };
    }

    public function zones(): array
    {
        return ['featured_image', 'gallery', 'attachments'];
    }

    public function isMultiple(string $zone): bool
    {
        return in_array($zone, ['gallery', 'attachments']);
    }
}

// config/media-zone.php
'models' => [
    App\Models\Post::class => App\MediaZone\PostMediaConfig::class,
],

protected function schedule(Schedule $schedule)
{
    $schedule->command('media-zone:cleanup')->daily();
}

// Model
class User extends Authenticatable
{
    use HasMediaZones;
}

// Controller
public function updateProfile(Request $request)
{
    $user = auth()->user();
    
    $user->syncMedia([
        'avatar' => [$request->avatar],
        'cover' => [$request->cover],
    ]);
    
    return back()->with('success', 'Profile updated!');
}

// Model
class Product extends Model
{
    use HasMediaZones;
}

// Accessor
protected function images(): Attribute
{
    return Attribute::make(
        get: fn() => $this->getMediaByZone('images'),
    );
}

// Display
foreach($product->images as $image) {
    echo "<img src='{$image->url}'>";
}

class Contract extends Model
{
    use HasMediaZones;
}

// config/media-zone.php
'routes' => [
    'enabled' => false,
],

// routes/web.php
use OKamal\LaravelMediaZone\Http\Controllers\MediaZoneController;

Route::post('/custom-upload', [MediaZoneController::class, 'store'])
    ->name('custom.upload');

$posts = Post::with('media')->get();

foreach ($posts as $post) {
    $post->featured_image; // No additional query
}

public function mediaStorageDirectory(?string $zone = null): string
{
    // Organize by user
    return "media/users/{$this->user_id}/posts/" . str($zone)->plural();
}
bash
php artisan vendor:publish --provider="OKamal\LaravelMediaZone\LaravelMediaZoneServiceProvider"
bash
# Publish config file
php artisan vendor:publish --tag=media-zone-config

# Publish migrations
php artisan vendor:publish --tag=media-zone-migrations

# Publish Vue component
php artisan vendor:publish --tag=media-zone-components
bash
php artisan migrate
bash
php artisan storage:link
bash
php artisan media-zone:cleanup