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


/avatar
  /avatar-360
/video
  /poster
    /poster-360
    /poster-720
  /360
  /720
  /1080
  /hls

namespace App\Models;

use Elegantly\Media\Concerns\HasMedia;
use Elegantly\Media\MediaCollection;
use Elegantly\Media\MediaConversion;
use Elegantly\Media\Enums\MediaType;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Spatie\Image\Enums\Fit;
use \App\Jobs\Media\OptimizedImageConversionJob;
use Elegantly\Media\Models\Media;
use Elegantly\Media\Contracts\InteractWithMedia;
use Illuminate\Contracts\Support\Arrayable;
use Elegantly\Media\Definitions\MediaConversionImage;
use Elegantly\Media\Definitions\MediaConversionPoster;

class Channel extends Model implements InteractWithMedia
{
    use HasMedia;

    public function registerMediaCollections(): Arrayable|iterable|null;
    {
       return [
            new MediaCollection(
                name: 'avatar',
                acceptedMimeTypes: [
                    'image/jpeg', 'image/png', 'image/gif', 'image/webp',
                ],
                transform: function($file){
                    Image::load($file->getRealPath())
                        ->fit(Fit::Crop, 500, 500)
                        ->optimize()
                        ->save();
                },
                conversions: [
                    new MediaConversionImage(
                        name: '360',
                        width: 360
                    ),
                ],
            )
            new MediaCollection(
                name: 'videos',
                acceptedMimeTypes: [
                    'video/mp4', 'video/webm', 'video/ogg', 'video/quicktime',
                ],
                conversions: [
                    new MediaConversionPoster(
                        name: 'poster',
                        conversions: [
                            new MediaConversionImage(
                                name: '360',
                                width: 360
                            ),
                        ],
                    ),
                ],
            )
       ];
    }
}

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ChannelAvatarController extends Controller
{
    function function store(Request $request, Channel $channel)
    {
        $channel->addMedia(
            file: $file->file('avatar'),
            collectionName: 'avatar',
            name: "{$channel->name}-avatar",
        )
    }
}

namespace App\Livewire;

use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
use Livewire\WithFileUploads;
use Livewire\Component;

class ImageUploader extends Component
{
    use WithFileUploads;

    function function save()
    {
        /** @var TemporaryUploadedFile */
        $file = $this->avatar;

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

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 Elegantly\Media\Concerns\HasMedia;
use Illuminate\Database\Eloquent\Model;
use Elegantly\Media\Contracts\InteractWithMedia;

class Channel extends Model implements InteractWithMedia
{
    use HasMedia;

}

namespace App\Models;

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

class Channel extends Model implements InteractWithMedia
{
    use HasMedia;

    public function registerMediaCollections(): Arrayable|iterable|null;
    {
       return [
            new MediaCollection(
                name: 'avatar',
                acceptedMimeTypes: [
                    'image/jpeg', 'image/png', 'image/gif', 'image/webp',
                ],
            )
            new MediaCollection(
                name: 'videos',
                acceptedMimeTypes: [
                    'video/mp4', 'video/webm', 'video/ogg', 'video/quicktime',
                ],
            )
       ];
    }
}

namespace App\Models;

use Elegantly\Media\Concerns\HasMedia;
use Elegantly\Media\MediaCollection;
use Elegantly\Media\MediaConversion;
use Elegantly\Media\Enums\MediaType;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Spatie\Image\Enums\Fit;
use \App\Jobs\Media\OptimizedImageConversionJob;
use Elegantly\Media\Models\Media;
use Elegantly\Media\Contracts\InteractWithMedia;
use Illuminate\Contracts\Support\Arrayable;
use Elegantly\Media\Support\ResponsiveImagesConversionsPreset;

class Channel extends Model implements InteractWithMedia
{
    use HasMedia;

    public function registerMediaCollections(): Arrayable|iterable|null;
    {
       return [
            new MediaCollection(
                name: 'avatar',
                acceptedMimeTypes: [
                    'image/jpeg', 'image/png', 'image/gif', 'image/webp',
                ],
                conversions: [
                    // using preset conversion definition
                    new MediaConversionImage(
                        name: '360',
                        width: 360,
                    ),
                    // using 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,
                            );

                        }
                    ),
                ]
            )
            new MediaCollection(
                name: 'videos',
                acceptedMimeTypes: [
                    'video/mp4', 'video/webm', 'video/ogg', 'video/quicktime',
                ],
                conversions: [
                    new MediaConversionPoster(
                        name: 'poster'
                    ),
                ]
            )
       ];
    }
}

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"