TabletopDOCS
Packages

Media library

tbtop/spatie-media-library: an image picker for tbtop/admin forms backed by one record's spatie/laravel-medialibrary collection, with upload and URL import.

This page documents tbtop/spatie-media-library v0.3.0. The package releases independently of tbtop/admin and works with tbtop/admin ^0.6.1. Source: DiVotek/tbtop-spatie-media-library.

What it is

The package adds one form field, $s->imageGallery(), that lists the files in one record's spatie/laravel-medialibrary collection, uploads new files into it, and imports images by URL. The field submits the ids of the picked media.

It is a field, not a media manager. Files belong to the record they are attached to: there is no shared pool, no folders and no browsing across records.

You needUse
Images that belong to one model already on spatie media collectionsimageGallery from this package
Files that editors reuse across recordsThe built-in media field
A single file stored as a path on a columnThe built-in upload field

Requirements: PHP 8.4, Laravel 11–13, spatie/laravel-medialibrary ^11, and @tbtop/inertia-admin ^0.6.1 with React 19 on the client.

Install

The package has a PHP half and a React half, published from the same tag. Install both:

composer require tbtop/spatie-media-library
npm install @tbtop/spatie-media-library

The service provider is auto-discovered. It registers the imageGallery field kind and one upload route per admin page. The package ships no migrations of its own: the media table is spatie's. If the app does not use spatie/laravel-medialibrary yet, publish and run its migration as spatie's installation guide describes.

Register the client field in resources/js/admin.tsx, before createInertiaApp() runs, the same place as any custom client component:

resources/js/admin.tsx
import { registerMediaLibraryField } from "@tbtop/spatie-media-library";

registerMediaLibraryField();

Tailwind skips node_modules, so declare the package's build as a source in resources/css/admin.css, or the field renders unstyled. The path is relative to the stylesheet:

resources/css/admin.css
@source "../../node_modules/@tbtop/spatie-media-library/dist";

Using the field in a form

The model implements spatie's HasMedia and declares the collection:

app/Models/Product.php
use Illuminate\Database\Eloquent\Model;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;

final class Product extends Model implements HasMedia
{
    use InteractsWithMedia;

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

On the edit page, bind the field to the record and the collection with forCollection(), and seed the form with the collection's current ids:

use Tbtop\Admin\Actions\ActionCtx;
use Tbtop\Admin\Actions\Effects;
use Tbtop\Admin\Dsl\Actions\FormActions;
use Tbtop\SpatieMediaLibrary\Support\MediaGalleryOptions;

$s->form('product', [
    $s->text('name')->label('Name')->required(),
    $s->imageGallery('photos')->label('Photos')
        ->forCollection($product, 'photos')
        ->multiple()
        ->rules('nullable|array'),
    $s->actionsRow([FormActions::save($s)]),
])
    ->record([
        'name' => $product->name,
        'photos' => MediaGalleryOptions::ids($product, 'photos'),
    ])
    ->onSubmit(function (ActionCtx $ctx) use ($product): Effects {
        $product->update(['name' => $ctx->form['name']]);

        if (array_key_exists('photos', $ctx->form)) {
            $ids = array_map('strval', (array) $ctx->form['photos']);

            MediaGalleryOptions::saveOrder($product, 'photos', $ids);
            // Optional and irreversible: delete media the editor removed from the field.
            // A cleared field arrives as null, becomes [] and deletes the whole collection.
            MediaGalleryOptions::pruneUnselected($product, 'photos', $ids);
        }

        return Effects::make()->notify('Saved');
    }),

forCollection() is the whole configuration. The client derives both endpoints from the page path, so the PHP side declares no URLs. imageGallery extends the core select, so multiple(), label(), rules() and the rest of the common field API work as usual.

The value is a media id as a string, or with multiple() a list of unique ids in the order the editor arranged them; an empty selection submits null. Like every field, it saves nothing on submit — the handler decides what the ids mean:

  • saveOrder() writes the order of the given ids to spatie's order_column, so getMedia() returns them in that order. Media of the collection that are not in the list keep their place after them. Ids from other records or collections are ignored. It deletes nothing.
  • pruneUnselected() deletes every media of the collection that is not in the list, rows and files. An empty list empties the collection: a cleared field (null) becomes [] in the example on purpose, while a request without the key skips both calls.

In the form, the field shows the picked images as tiles and a "+" tile. Clicking a tile replaces that one image; the × on a tile removes it from the selection. With multiple() the tiles can be dragged into a new order, or lifted with Space, moved with the arrow keys and dropped with Space. Replacing a tile with an image already picked in another tile leaves one tile for it. A picked id whose media no longer exists shows as a "Missing image" tile that can still be removed or replaced. The picker dialog searches the collection by media name. Non-image files in the collection show as a file icon labelled with their MIME subtype (for example pdf). In a table, the cell shows the count, such as "3 images".

The record must be saved. Spatie builds the storage path from the model key, so an upload to an unsaved model is refused with a 422. Use the field on edit pages, or drop it from a create page with ->when($product->exists).

Uploading and URL import

The picker dialog has an Upload button and a URL input. Both post to {page-path}/gallery-upload/{field}, a route the package registers for every page of every panel in tbtop-admin.panels. The route runs under the same middleware as the page's other endpoints — the page's middleware() override when it has one, the panel's auth stack otherwise — and the page's can() gate applies on top. The target record and collection are read from the field on the re-resolved page, never from the request, so a caller cannot redirect an upload into another model.

A stored file is added to the collection at once, before the form is saved. It appears first in the dialog, pre-selected, even when the collection already holds per_page files. On a singleFile() or onlyKeepLatest() collection spatie deletes the older files at that moment, so cancelling the dialog or the form does not bring them back.

On the way in:

  • Size. Capped at tbtop-admin.media.max_size (kilobytes, 10 MiB by default), for uploads and imports alike.
  • Type. The detected MIME type must match the package's accept list. text/html is refused whatever the list says.
  • Conversion. Raster images are re-encoded to conversion.format with the original name and a new extension. GD keeps the first frame of an animated GIF and drops EXIF metadata, including orientation. Set conversion.format to null if you need animation or camera orientation preserved. A format GD cannot encode, or a file GD cannot decode, is stored unchanged. When the collection declares acceptsMimeTypes() and the converted type is not in it, the original file is stored unconverted.
  • SVG. An SVG, detected from its content rather than its claimed type, is sanitised before it reaches the collection. One that cannot be sanitised is refused with a 422 and core's translated svg_invalid text; no row is written, and on a singleFile() collection the previous file stays.

Spatie's own checks run after these. A file the collection refuses gets a 422 with a short reason — "That file type is not allowed for this collection.", "The file is too large." or "This file cannot be added to this collection." — never spatie's message, which can carry server paths. A disk that is missing or cannot be accessed is a server error and stays a 500.

URL import uses core's fetcher: private address ranges and non-HTTP schemes are blocked with DNS pinning, redirects are refused, the download aborts past the size cap, and the MIME type is checked from the downloaded bytes. The timeout (tbtop-admin.media.url_import.timeout, 30 seconds) and the host allowlist (tbtop-admin.media.url_import.allowed_hosts) come from core's config. The import runs synchronously inside the request.

Files are stored on the disk spatie is configured to use, not on tbtop-admin.media.disk.

Configuration

Publish the config file to change the defaults:

php artisan vendor:publish --tag=tbtop-spatie-media-library-config
KeyDefaultMeaning
per_page24Most rows the picker lists per request
conversion.format'webp'Re-encode format: webp, jpeg or png; null keeps the original
conversion.quality80Encoder quality
accept['image/*']Allowed MIME types, as fnmatch patterns
url_import.enabledtrueWhether URL import is accepted. When false the input still shows in the dialog, and an import returns a 422 'URL import is disabled.'

These settings are global. The field has no per-field override for format, accepted types or limits.

Limitations

What v0.3.0 does not do:

  • Nothing is saved by the field. Order and deletions reach the collection only through saveOrder() and pruneUnselected() in your handler; uploads are the exception, see above.
  • Abandoned uploads stay. A file uploaded in a dialog that is cancelled, or in a form that is never saved, remains in the collection; nothing removes it until a later save runs pruneUnselected().
  • No shared library. Only the bound record's collection is listed. For files reused across records, use the core media field.
  • No cropping, alt text or custom properties. Edit those through spatie's API in your own code.
  • The dialog lists at most per_page files, without pagination. Search narrows by name. Picked files beyond that cap still show as tiles.
  • The browser file dialog offers images only. Widening accept affects URL import and server checks; the Upload button's dialog still filters to image/*.
  • English-only interface. The dialog's labels and messages are not translated.

On this page