PHP code example of elegantly / laravel-media

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

    

elegantly / laravel-media example snippets


use Elegantly\Media\Jobs\DeleteModelMediaJob;
use Elegantly\Media\Models\Media;

return [
    /**
     * The media model
     * Define your own model here by extending \Elegantly\Media\Models\Media::class
     */
    'model' => Media::class,

    /**
     * The path used to store temporary file copy for conversions
     * This will be used with storage_path() function
     */
    'temporary_storage_path' => 'app/tmp/media',

    /**
     * The default disk used for storing files
     */
    'disk' => env('MEDIA_DISK', env('FILESYSTEM_DISK', 'local')),

    /**
     * Determine if media should be deleted with the model
     * when using the HasMedia Trait
     */
    'delete_media_with_model' => true,

    /**
     * Determine if media should be deleted with the model
     * when it is soft deleted
     */
    'delete_media_with_trashed_model' => false,

    /**
     * Deleting a large number of media attached to a model can be time-consuming
     * or even fail (e.g., cloud API error, permissions, etc.)
     * For performance and monitoring, when a model with the HasMedia trait is deleted,
     * each media is individually deleted inside a job.
     */
    'delete_media_with_model_job' => DeleteModelMediaJob::class,

    /**
     * The default collection name
     */
    'default_collection_name' => 'default',

    /**
     * Prefix for the generated path of files
     * Set to null if you do not want any prefix
     * To fully customize the generated default path, extend the Media model and override the generateBasePath method
     */
    'generated_path_prefix' => null,

    /**
     * Customize the queue connection used when dispatching conversion jobs
     */
    'queue_connection' => env('QUEUE_CONNECTION', 'sync'),

    /**
     * Customize the queue used when dispatching conversion jobs
     * null will fall back to the default Laravel queue
     */
    'queue' => null,

];

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Elegantly\Media\Concerns\HasMedia;
use Elegantly\Media\Contracts\InteractWithMedia;
use Elegantly\Media\MediaCollection;

class Channel extends Model implements InteractWithMedia
{
    use HasMedia;

    public function registerMediaCollections(): array;
    {
        return [
            new MediaCollection(
                name: 'avatar',
                single: true, // If true, only the latest file will be kept
                disk: 's3', // (optional) Specify where the file will be stored
                acceptedMimeTypes: [ // (optional) Specify accepted file types
                    'image/jpeg',
                    'image/png',
                    'image/webp'
                ]
            )
        ];
    }
}

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Elegantly\Media\Concerns\HasMedia;
use Elegantly\Media\Contracts\InteractWithMedia;
use Elegantly\Media\MediaCollection;
use Elegantly\Media\Definitions\MediaConversionImage;

class Channel extends Model implements InteractWithMedia
{
    use HasMedia;

    public function registerMediaCollections(): array;
    {
        return [
            new MediaCollection(
                name: 'videos',
                conversions: [
                    new MediaConversionPoster(
                        name: 'poster',
                        conversions: [
                            new MediaConversionImage(
                                name: '360p',
                                width: 360
                            ),
                        ],
                    ),
                    new MediaConversionVideo(
                        name: '720p',
                        width: 720
                    ),
                ]
            )
        ];
    }
}

public function store(Request $request, Channel $channel)
{
    $channel->addMedia(
        file: $request->file('avatar'),
        collectionName: 'avatar',
        name: "{$channel->name}-avatar"
    );
}

use Livewire\WithFileUploads;

class ImageUploader extends Component
{
    use WithFileUploads;

    public function save()
    {
        $this->channel->addMedia(
            file: $this->avatar->getRealPath(),
            collectionName: 'avatar',
            name: "{$this->channel->name}-avatar"
        );
    }
}

// Get all media from a specific collection
$avatars = $channel->getMedia('avatar');

// Get the first media from a collection
$avatar = $channel->getFirstMedia('avatar');

// Check if media exists
$hasAvatar = $channel->hasMedia('avatar');

$media = $channel->getFirstMedia('avatar');

// File properties
$media->name; // file_name without the extension
$media->file_name;
$media->extension;
$media->mime_type;
$media->size; // in bytes
$media->humanReadableSize();

// Image/Video specific properties
$media->width;       // in pixels
$media->height;      // in pixels
$media->aspect_ratio;
$media->duration;    // for video/audio

// Get the original media URL
$originalUrl = $media->getUrl();

// Get a specific conversion URL
$thumbnailUrl = $media->getUrl(
    conversion: '360p',
    fallback: true // Falls back to original if conversion doesn't exist
);

// Use the same logic with other properties such as
$media->getPath();
$media->getWith();
// ...

// Check if a conversion exists
$hasThumbnail = $media->hasConversion('avatar.100p');

// Get a specific conversion
$thumbnailConversion = $media->getConversion('avatar.100p');

// Get the 'avatar' conversion
$media->getParentConversion('avatar.360p');

// Only get children conversions of avatar
$media->getChildrenConversions('avatar');

new MediaCollection(
    name: 'avatar',
    conversions: [
        new MediaConversionImage(
            name: '360',
            width: 360,
            queued: true,  // (default) Dispatch as a background job
            queue: 'slow' // (optional) Specify a custom queue
        )
    ]
)

new MediaCollection(
    name: 'avatar',
    conversions: [
        new MediaConversionImage(
            name: '360',
            width: 360,
            immediate: false, // Conversion will not be generated at upload time
        )
    ]
)

// Generate the conversion synchronously
$media->executeConversion(
    conversion: '360',
    force: false // Skips execution if the conversion already exists
);

// Dispatch the conversion as a background job
$media->dispatchConversion(
    conversion: '360',
    force: false // Skips execution if the conversion already exists
);

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Elegantly\Media\Concerns\HasMedia;
use Elegantly\Media\Contracts\InteractWithMedia;
use Elegantly\Media\MediaCollection;
use Elegantly\Media\Definitions\MediaConversionDefinition;

class Channel extends Model implements InteractWithMedia
{
    use HasMedia;

    public function registerMediaCollections(): array
    {
        return [
            new MediaCollection(
                name: 'videos',
                conversions: [
                    // Using a custom conversion definition
                    new MediaConversionDefinition(
                        name: 'webp',
                        when: fn($media, $parent) => $media->type === MediaType::Image,
                        handle: function($media, $parent, $file, $filesystem, $temporaryDirectory) {
                            $target = $filesystem->path("{$media->name}.webp");

                            Image::load($filesystem->path($file))
                                ->optimize($this->optimizerChain)
                                ->save($target);

                            return $media->addConversion(
                                file: $target,
                                conversionName: $this->name,
                                parent: $parent,
                            );
                        }
                    ),
                ]
            ),
        ];
    }
}

// Store a new file as a conversion
$media->addConversion(
    file: $file, // Can be an HTTP File, URL, or file path
    conversionName: 'transcript',
    parent: $mediaConversion // (Optional) Specify a parent conversion
    // Additional parameters...
);

// Replace an existing conversion safely
$media->replaceConversion(
    conversion: $mediaConversion
);

// Safely delete a specific conversion and all its children
$media->deleteConversion('360');

// Safely delete only the child conversions of a parent conversion
$media->deleteChildrenConversions('360');

// Dispatch or execute a conversion
$media->dispatchConversion('360'); // Runs asynchronously as a job
$media->executeConversion('360'); // Executes synchronously
$media->getOrExecuteConversion('360'); // Retrieves or generates the conversion

// Retrieve conversion information
$media->getConversion('360'); // Fetch a specific conversion
$media->hasConversion('360'); // Check if a conversion exists
$media->getParentConversion('360'); // Retrieve the parent of a conversion
$media->getChildrenConversions('360'); // Retrieve child conversions

namespace App\Models;

use Elegantly\Media\Models\Media as ElegantlyMedia;

class Media extends ElegantlyMedia
{
    // ...
}

use App\Models\Media;

return [

    'model' => Media::class,

    // ...

];

namespace App\Models;

use App\Models\Media;
use Elegantly\Media\Concerns\HasMedia;
use Elegantly\Media\Contracts\InteractWithMedia;

/**
 * @implements InteractWithMedia<Media>
 */
class Post extends Model implements InteractWithMedia
{
    /** @use HasMedia<Media> **/
    use HasMedia;

    // ...
}
bash
php artisan vendor:publish --tag="laravel-media-migrations"
php artisan migrate
bash
php artisan vendor:publish --tag="laravel-media-config"
bash
php artisan vendor:publish --tag="laravel-media-views"
bash
php artisan media:generate-conversions