Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Gallery Json Media Laravel Package

webplusm/gallery-json-media

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup Steps

  1. Install the Package

    composer require webplusm/gallery-json-media
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="Webplusm\GalleryJsonMedia\GalleryJsonMediaServiceProvider" --tag="config"
    
  2. Configure the Model Add a JSON column (e.g., gallery) to your database table:

    Schema::table('your_table', function (Blueprint $table) {
        $table->json('gallery')->nullable();
    });
    
  3. Register in Filament Resource Use the GalleryJsonMedia trait in your Filament resource:

    use Webplusm\GalleryJsonMedia\Traits\HasGalleryJsonMedia;
    
    class YourResource extends Resource {
        use HasGalleryJsonMedia;
    
        // ...
    }
    
  4. First Use Case: Displaying Media Use the provided Blade component in your view:

    @galleryJsonMedia('gallery')
    

Implementation Patterns

Core Workflows

1. Managing Media in Filament

  • Adding Media: Use the GalleryJsonMedia field in your Filament form:

    use Webplusm\GalleryJsonMedia\Fields\GalleryJsonMedia;
    
    public static function form(Form $form): array {
        return [
            GalleryJsonMedia::make('gallery')
                ->label('Media Gallery')
                ->required(),
        ];
    }
    
  • Fluent API for Media Manipulation:

    // Add a single image
    $model->gallery()->addImage('path/to/image.jpg', ['alt' => 'Description']);
    
    // Add multiple images
    $model->gallery()->addImages([
        'path/to/image1.jpg',
        'path/to/image2.jpg',
    ]);
    
    // Add a document
    $model->gallery()->addDocument('path/to/document.pdf', ['title' => 'Document']);
    

2. Frontend Display with Blade Components

  • Basic Gallery Display:

    @galleryJsonMedia('gallery')
    

    Renders all images and documents in a responsive grid.

  • Customizing Display:

    @galleryJsonMedia('gallery', [
        'showDocuments' => false, // Hide documents
        'imageClass' => 'w-1/3',  // Custom CSS class for images
    ])
    

3. Custom Properties

  • Adding Metadata:

    $model->gallery()->addImage('image.jpg', [
        'alt' => 'Custom Alt Text',
        'position' => 1, // Order in gallery
        'tags' => ['tag1', 'tag2'],
    ]);
    
  • Retrieving Metadata:

    $images = $model->gallery->images;
    foreach ($images as $image) {
        echo $image->alt; // Access custom properties
    }
    

4. API Integration

  • Fluent API for API Responses:

    return response()->json([
        'gallery' => $model->gallery->toArray(),
    ]);
    
  • Filtering in API: Use the GalleryJsonMedia query builder methods:

    $model->gallery()->where('alt', 'like', '%description%');
    

Integration Tips

1. With Filament Panels

  • Resource-Level Integration: Ensure your resource extends Filament\Resources\Resource and includes the trait:

    class PostResource extends Resource {
        use HasGalleryJsonMedia;
    
        // ...
    }
    
  • Widget Integration: Create a custom widget to display galleries:

    class GalleryWidget extends Widget {
        public function getView(): string {
            return view('widgets.gallery', [
                'gallery' => $this->getGalleryData(),
            ]);
        }
    }
    

2. With Laravel Scout (Search)

  • Indexing Custom Properties: Extend the ToSearchableArray method in your model:
    public function toSearchableArray(): array {
        return [
            'gallery' => $this->gallery->images->pluck('alt'),
        ];
    }
    

3. With Storage Systems

  • Custom Storage Paths: Configure the storage path in config/gallery-json-media.php:
    'storage' => [
        'disk' => 'public',
        'path' => 'galleries',
    ],
    

4. With Filament Actions

  • Bulk Actions: Add a bulk action to delete gallery items:
    public static function getBulkActions(): array {
        return [
            Actions\DeleteBulkGalleryAction::make(),
        ];
    }
    

Gotchas and Tips

Pitfalls and Debugging

1. JSON Column Constraints

  • Issue: MySQL JSON column may throw errors if data is malformed. Fix: Validate the JSON structure before saving:

    $model->gallery = json_encode($model->gallery);
    
  • Tip: Use ->nullable() on the JSON column to avoid strict validation.

2. File Upload Handling

  • Issue: Large files may exceed PHP upload limits. Fix: Adjust php.ini or use chunked uploads:

    ini_set('post_max_size', '256M');
    ini_set('upload_max_filesize', '256M');
    
  • Tip: Use Symfony\Component\HttpFoundation\File\UploadedFile for manual handling.

3. Caching and Performance

  • Issue: Frequent JSON serialization/deserialization can slow queries. Fix: Cache the parsed JSON in a model accessor:
    public function getGalleryAttribute($value) {
        return cache()->remember("gallery_{$this->id}", now()->addHours(1), function() use ($value) {
            return json_decode($value, true);
        });
    }
    

4. Migration Conflicts

  • Issue: Adding a JSON column to an existing table may cause downtime. Fix: Use a migration with a backup:
    Schema::table('your_table', function (Blueprint $table) {
        $table->json('gallery')->nullable()->after('other_column');
    });
    

5. Filament Field Conflicts

  • Issue: The GalleryJsonMedia field may conflict with other Filament fields. Fix: Use unique namespacing:
    GalleryJsonMedia::make('custom.gallery')
        ->label('Custom Gallery')
    

Configuration Quirks

1. Default Values

  • Setting Default Gallery:
    public static function getDefaultGallery(): array {
        return [
            'images' => [],
            'documents' => [],
        ];
    }
    

2. Customizing Blade Components

  • Overriding Views: Publish the package views:
    php artisan vendor:publish --tag="gallery-json-media-views"
    
    Then override in resources/views/vendor/gallery-json-media/.

3. API Response Formatting

  • Custom Serialization: Extend the GalleryJsonMedia class to modify API responses:
    class CustomGalleryJsonMedia extends GalleryJsonMedia {
        public function toArray(): array {
            return [
                'images' => array_map(fn($image) => [
                    'url' => $image->url,
                    'thumbnail' => $this->getThumbnailUrl($image->url),
                ], $this->images),
            ];
        }
    }
    

Extension Points

1. Adding Custom Media Types

  • Extend the Base Class:
    class VideoGalleryJsonMedia extends GalleryJsonMedia {
        public function addVideo(string $url, array $metadata = []): self {
            $this->videos[] = [
                'url' => $url,
                ...$metadata,
            ];
            return $this;
        }
    }
    

2. Custom Storage Drivers

  • Implement a Driver:
    namespace App\Services;
    
    use Webplusm\GalleryJsonMedia\Contracts\StorageDriver;
    
    class S3StorageDriver implements StorageDriver {
        public function store($file, $path) {
            // Custom S3 logic
        }
    }
    
    Register in config:
    'storage_driver' => \App\Services\S3StorageDriver::class,
    

3. Event Listeners

  • Trigger on Media Changes:
    class GalleryUpdatedListener {
        public function handle($event) {
            // Log or process gallery updates
        }
    }
    
    Register in EventServiceProvider:
    protected $listen = [
        \Webplusm\GalleryJsonMedia\Events\GalleryUpdated::class => [
            GalleryUpdatedListener::class,
        ],
    ];
    

4. Custom Validation

  • Validate Gallery Content:
    use Webplusm\GalleryJsonMedia\Rules\ValidGallery;
    
    public function rules(): array {
        return [
            'gallery' => ['required', new ValidGallery],
        ];
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor