PHP code example of tbtop / spatie-media-library

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

    

tbtop / spatie-media-library example snippets


use Illuminate\Database\Eloquent\Model;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;

final class Post extends Model implements HasMedia
{
    use InteractsWithMedia;

    public function registerMediaCollections(): void
    {
        $this->addMediaCollection('banners');
    }
}

use Tbtop\SpatieMediaLibrary\Support\MediaGalleryOptions;

$s->form('post', [
    $s->imageGallery('banners')
        ->label('Post banners')
        ->forCollection($post, 'banners')
        ->multiple()
        ->rules('nullable|array'),
])->record(['banners' => MediaGalleryOptions::ids($post, 'banners')]);

->onSubmit(function (ActionCtx $ctx) use ($post): void {
    if (! array_key_exists('banners', $ctx->form)) {
        return; // field not submitted: leave the collection alone
    }
    $ids = array_map('strval', (array) $ctx->form['banners']);

    MediaGalleryOptions::saveOrder($post, 'banners', $ids);
    // Optional, irreversible: delete media the admin removed from the field.
    MediaGalleryOptions::pruneUnselected($post, 'banners', $ids);
})
bash
php artisan vendor:publish --tag=tbtop-spatie-media-library-config