Advanced Nova Media Library

repository·master·Indexed 20 days ago

https://github.com/ebess/advanced-nova-media-library

A Laravel Nova package extending Spatie's MediaLibrary to provide advanced image and file management. Features include drag-and-drop reordering, image cropping, responsive image support, and video handling via the Media field. It provides specialized Images and Files fields for managing single or multiple uploads, custom property metadata, and support for temporary S3 URLs and Laravel Vapor uploads.

Tokens
4.5K
Snippets
26
Records
26
Agent score
69%

What's inside advanced-nova-media-library

  1. Configure Spatie MediaLibrary on your Model

    master

    Before using the Nova fields, ensure your Eloquent model is configured to use Spatie's MediaLibrary. You must implement registerMediaConversions to define image sizes and registerMediaCollections to define the collections used by the Nova fields.

    use Spatie\MediaLibrary\MediaCollections\Models\Media;
    
    public function registerMediaConversions(Media $media = null): void
    {
        $this->addMediaConversion('thumb')
            ->width(130)
            ->height(130);
    }
    
    public function registerMediaCollections(): void
    {
        $this->addMediaCollection('main')->singleFile();
        $this->addMediaCollection('my_multi_collection');
    }
  2. Enable selecting existing media

    master

    To allow users to select media that has already been uploaded to other models (which will copy the file), you must perform three steps:

    1. Publish the config files if not already done: php artisan vendor:publish --tag=nova-media-library.
    2. Enable the feature in config/nova-media-library.php by setting 'enable-existing-media' => true.
    3. Call enableExistingMedia() on your Images field.

    Warning: This exposes an endpoint that allows users to search existing media. Do not enable this if your media/custom properties are confidential. This feature does not support temporary URLs.

    // 1. In config/nova-media-library.php
    'enable-existing-media' => true,
    
    // 2. In your Nova Resource
    Images::make('Image')->enableExistingMedia(),
  3. Run the development environment via Docker Compose

    master

    The project includes a docker-compose.yml file to orchestrate a Node.js environment. It uses a node:10.11 image and automatically runs yarn install followed by yarn prod upon startup. The local directory is mounted to /app within the container.

    version: '3'
    services:
        node:
            image: node:10.11
            working_dir: /app
            volumes:
                - .:/app
            command: sh -c "yarn install && yarn prod"
  4. Generate temporary URLs for S3 storage

    master

    If storing media on Amazon S3, use the temporary() method to generate signed URLs. This method requires a Carbon instance specifying the expiration time.

    Images::make('Image 1', 'img1')
        ->temporary(now()->addMinutes(5));
    
    Files::make('Multiple files', 'multiple_files')
        ->temporary(now()->addMinutes(10));
  5. Upload single images with the Images field

    master

    The Images field allows for single image uploads. You can specify which media collection to use as the second parameter and define which conversion to use for the index view.

    use Ebess\AdvancedNovaMediaLibrary\Fields\Images;
    
    public function fields(Request $request)
    {
        return [
            Images::make('Main image', 'main') // 'main' is the media collection name
                ->conversionOnIndexView('thumb') // conversion used to display the image
                ->rules('required'),
        ];
    }
  6. Add custom properties to media fields

    master

    You can attach custom Nova fields to your media fields to manage metadata associated with the media.

    • Use customPropertiesFields([...]) to provide user input for properties (e.g., Boolean, Markdown).
    • Use customProperties([...]) to set properties programmatically without user input.
    // With user input
    Images::make('Gallery')
        ->customPropertiesFields([
            Boolean::make('Active'),
            Markdown::make('Description'),
        ]);
    
    // Without user input (programmatic)
    Files::make('Multiple files', 'multiple_files')
        ->customProperties([
            'foo' => auth()->user()->foo,
        ]);
  7. Configure image cropping

    master

    Cropping and rotating are enabled by default for image/jpg, image/jpeg, and image/png via a scissors icon in the edit view.

    Note: Cropping an existing image deletes the original media model and replaces it with the cropped version, though custom properties are preserved.

    • Disable cropping for a field: ->croppable(false).
    • Set specific aspect ratios or configs: ->croppingConfigs(['aspectRatio' => 4/3]).
    • Enforce cropping on upload: ->mustCrop().
    • Disable globally: Set 'default-croppable' => false in config/nova-media-library.php.
    Images::make('Gallery')
        ->croppingConfigs(['aspectRatio' => 4/3])
        ->mustCrop();
  8. Customize uploaded filenames and names

    master

    You can control the filename and the 'name' attribute of the uploaded media using callbacks.

    • setFileName(callback): The callback receives ($originalFilename, $extension, $model). Use this to change the actual file path/name.
    • setName(callback): The callback receives ($originalFilename, $model). Use this to change the 'name' field on the Media object (defaults to original filename without extension).
    // Set filename to MD5 hash
    Images::make('Image 1', 'img1')
        ->setFileName(function($originalFilename, $extension, $model){
            return md5($originalFilename) . '.' . $extension;
        });
    
    // Set the Media object name to MD5 hash
    Images::make('Image 1', 'img1')
        ->setName(function($originalFilename, $model){
            return md5($originalFilename);
        });
  9. Upload and order multiple images with the Images field

    master

    By using the Images field with a collection name, you enable multiple image uploads. This feature includes drag-and-drop functionality to reorder images. You can configure different conversions for the preview, detail, index, and form views.

    use Ebess\AdvancedNovaMediaLibrary\Fields\Images;
    
    public function fields(Request $request)
    {
        return [
            Images::make('Images', 'my_multi_collection')
                ->conversionOnPreview('medium-size')
                ->conversionOnDetailView('thumb')
                ->conversionOnIndexView('thumb')
                ->conversionOnForm('thumb')
                ->fullSize()
                ->rules('required', 'size:3')
                ->singleImageRules('dimensions:min_width=100'),
        ];
    }
  10. Use the Media field for video handling

    master

    To handle video uploads with thumbnails, use the Media field instead of Images. This allows the field to process video files. Ensure your model's registerMediaConversions includes a conversion that extracts a video frame (e.g., using extractVideoFrameAtSecond).

    // In Nova Resource
    use Ebess\AdvancedNovaMediaLibrary\Fields\Media;
    
    Media::make('Gallery')
        ->conversionOnIndexView('thumb')
        ->singleMediaRules('max:5000');
    
    // In Model
    public function registerMediaConversions(Media $media = null): void
    {
        $this->addMediaConversion('thumb')
            ->width(368)
            ->height(232)
            ->extractVideoFrameAtSecond(1);
    }