PHP code example of dialloibrahima / laravel-model-media

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

    

dialloibrahima / laravel-model-media example snippets


namespace App\Models;

use DialloIbrahima\HasMedia\HasMedia;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    use HasMedia;

    protected static function booted()
    {
        self::registerMediaForColumn(
            column: 'profile_photo',    // Your DB column
            directory: 'avatars',       // Storage folder
            fileName: 'id',             // Name file after a model attribute (or use a Closure)
            disk: 'public'              // Optional: storage disk (default is 'public')
        );
    }
}

public function update(Request $request, User $user)
{
    if ($request->hasFile('photo')) {
        // This method automatically saves the model for you!
        $user->attachMedia($request->file('photo'), 'profile_photo');
    }

    return back();
}

// Remove media and clear the column
$user->detachMedia('profile_photo');

// Media is also automatically deleted when the model is deleted
$user->delete(); // Files are cleaned up automatically

protected static function registerMediaForColumn(
    string $column,              // Database column name
    string $directory,           // Storage directory
    string|Closure $fileName,    // Attribute name or Closure for filename
    string $disk = 'public'      // Storage disk
): void

public function attachMedia(UploadedFile $file, string $column): bool

public function detachMedia(?string $column): bool

public function getMediaUrl(string $column): ?string

public function getMediaMappings(): array

public function getGlideUrl(
    string $column,              // Column name
    array $params = [],          // Glide transformation parameters
    bool $throwOnError = false   // Throw exception on error
): ?string

// Basic resize
$user->getGlideUrl('avatar', ['w' => 200, 'h' => 200]);

// Crop to square
$user->getGlideUrl('avatar', ['w' => 300, 'h' => 300, 'fit' => 'crop']);

// Convert to WebP
$user->getGlideUrl('avatar', ['w' => 400, 'fm' => 'webp', 'q' => 85]);

// With error handling
try {
    $url = $user->getGlideUrl('document', ['w' => 200], throwOnError: true);
} catch (InvalidMediaTypeException $e) {
    // Handle non-image file
}

public function getGlidePresetUrl(
    string $column,              // Column name
    string $preset,              // Preset name from config
    bool $throwOnError = false   // Throw exception on error
): ?string

// Use thumbnail preset (defined in config)
$user->getGlidePresetUrl('avatar', 'thumbnail');

// Use medium preset
$user->getGlidePresetUrl('cover', 'medium');

public function getGlideSrcset(
    string $column,                               // Column name
    array $widths = [400, 800, 1200, 1600],       // Image widths
    bool $throwOnError = false                    // Throw exception on error
): ?string

// Default widths
$srcset = $user->getGlideSrcset('cover');
// Result: "http://...?w=400&fm=webp 400w, http://...?w=800&fm=webp 800w, ..."

// Custom widths for mobile-first
$srcset = $user->getGlideSrcset('hero', [375, 768, 1024, 1920]);

public function hasImageMedia(string $column): bool

use Illuminate\Support\Str;

self::registerMediaForColumn(
    column: 'invoice_pdf',
    directory: 'invoices',
    fileName: fn ($model, $file) => "invoice-{$model->number}-" . Str::random(5)
);
// Result: invoice-INV-001-x7kP2.pdf

// Store avatars on public disk
self::registerMediaForColumn(
    column: 'avatar',
    directory: 'avatars',
    fileName: 'id',
    disk: 'public'
);

// Store private documents on S3
self::registerMediaForColumn(
    column: 'contract',
    directory: 'contracts',
    fileName: fn ($model) => "contract-{$model->id}",
    disk: 's3'
);

use DialloIbrahima\HasMedia\HasMedia;
use DialloIbrahima\HasMedia\Plugins\Glide\HasGlideUrls;

class User extends Model
{
    use HasMedia, HasGlideUrls;

    // ...
}

// Resize to 200x200
$url = $user->getGlideUrl('avatar', ['w' => 200, 'h' => 200]);

// Crop to fit
$url = $user->getGlideUrl('avatar', ['w' => 300, 'h' => 300, 'fit' => 'crop']);

// Use a preset defined in config
$url = $user->getGlidePresetUrl('avatar', 'thumbnail');

// Get a responsive srcset
$srcset = $user->getGlideSrcset('avatar');

// config/model-media-glide.php
'presets' => [
    'thumbnail' => [
        'w' => 200,
        'h' => 200,
        'fit' => 'crop',
        'fm' => 'webp',
        'q' => 90,
        'or' => 'auto',
    ],
    'medium' => [
        'w' => 800,
        'h' => 600,
        'fit' => 'contain',
        'fm' => 'webp',
        'q' => 85,
        'or' => 'auto',
    ],
    'og-image' => [
        'w' => 1200,
        'h' => 630,
        'fit' => 'crop',
        'fm' => 'jpg',  // Facebook/LinkedIn don't support webp
        'q' => 85,
        'or' => 'auto',
    ],
],

$thumbnailUrl = $user->getGlidePresetUrl('avatar', 'thumbnail');
$ogImageUrl = $post->getGlidePresetUrl('cover', 'og-image');

use DialloIbrahima\HasMedia\Plugins\Glide\Facades\Glide;

// Generate a URL for a specific path
$url = Glide::url('avatars/user-1.jpg', ['w' => 200, 'fit' => 'crop']);

// Use a preset
$url = Glide::preset('posts/cover.png', 'medium');

// Generate a responsive srcset
$srcset = Glide::srcset('products/hero.webp', [400, 800, 1200]);

// Clear cache for a specific file
Glide::deleteCache('avatars/user-1.jpg');

// config/model-media-glide.php
return [
    // Routes
    'routes_enabled' => true,
    'route_prefix' => 'media',
    'middleware' => ['web'],

    // Security (URL Signing)
    'secure' => env('GLIDE_SECURE', false),
    'signature_key' => env('GLIDE_SIGNATURE_KEY', ''),

    // Storage Disks (supports S3, R2, and any Flysystem driver)
    'source_disk' => env('GLIDE_SOURCE_DISK', 'public'),
    'source_path_prefix' => env('GLIDE_SOURCE_PATH_PREFIX', ''),

    'cache_disk' => env('GLIDE_CACHE_DISK', 'local'),
    'cache_path' => env('GLIDE_CACHE_PATH', 'glide-cache'),

    'watermarks_disk' => env('GLIDE_WATERMARKS_DISK', 'local'),
    'watermarks_path' => env('GLIDE_WATERMARKS_PATH', 'watermarks'),

    // Server
    'driver' => env('GLIDE_DRIVER', 'imagick'), // 'imagick' recommended over 'gd'
    'max_image_size' => env('GLIDE_MAX_IMAGE_SIZE', 4000 * 4000), // 16MP

    // Presets (reusable transformation sets)
    'presets' => [
        'avatar' => ['w' => 110, 'h' => 110, 'fit' => 'crop', 'fm' => 'webp', 'q' => 90, 'or' => 'auto'],
        'thumbnail' => ['w' => 200, 'h' => 200, 'fit' => 'crop', 'fm' => 'webp', 'q' => 90, 'or' => 'auto'],
        // ...
    ],
];

use DialloIbrahima\HasMedia\Plugins\Glide\Facades\Glide;

Glide::deleteCache('avatars/user-1.jpg');
blade
<img src="{{ $user->getMediaUrl('profile_photo') }}">
blade
<img
    src="{{ $post->getGlideUrl('cover', ['w' => 800]) }}"
    srcset="{{ $post->getGlideSrcset('cover') }}"
    sizes="(max-width: 768px) 100vw, 800px"
    alt="{{ $post->title }}"
>
bash
php artisan vendor:publish --tag=model-media-glide-config
blade
<picture>
    <source
        srcset="{{ $post->getGlideSrcset('cover', [375, 768, 1024, 1920]) }}"
        sizes="(max-width: 768px) 100vw, (max-width: 1024px) 50vw, 33vw"
    >
    <img
        src="{{ $post->getGlideUrl('cover', ['w' => 800]) }}"
        alt="{{ $post->title }}"
        loading="lazy"
    >
</picture>
bash
php artisan vendor:publish --tag=model-media-glide-config
bash
php artisan optimize
bash
php artisan tinker
>>> Str::random(32)