Search by

mohmmadshabrani / laravel-image-engine

Moh_sh

Resumable, checksum-verified image uploads for Laravel: straight to S3 or through your app, checked again on the server, with resized variants and a browser upload queue.

Package info

github.com/Mohmmadshabrani/laravel-image-engine

pkg:composer/mohmmadshabrani/laravel-image-engine

Statistics

Installs: 70

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v1.0.0 2026-12-05 15:07 UTC

This package is auto-updated.

Last update: 2026-12-05 15:36:19 UTC


README

Image uploads for Laravel that survive weak connections and do not trust the browser.

  • Resumable. A file is sent in 5 MiB parts. After a dropped connection, a reload or a closed tab, the upload carries on from the parts already stored.
  • Verified twice. The browser sends a SHA-256 for the whole file and for each part, so S3 itself refuses a part that changed on the way. After the upload, Laravel checks the stored object again: its size, its magic bytes and its full checksum.
  • Straight to S3, or through your app. S3 disks get signed URLs, so bytes never pass through PHP. Any other disk receives the parts through Laravel, so local development and tests need no bucket.
  • Variants. A queued job applies the EXIF orientation, strips metadata and writes the resized copies each place needs, with an optional watermark. The original is never changed.
  • Attached in your transaction. An upload belongs to nobody until your own save claims it. A failed save leaves it unclaimed, and a nightly command deletes what was never claimed.
  • A browser queue. A framework-free TypeScript engine hashes, shrinks, uploads three files at a time, retries with backoff and keeps its queue in IndexedDB. React bindings and a service worker that finishes uploads in the background are included.

It accepts JPEG, PNG and WebP.

Requirements

  • PHP 8.3 or newer, Laravel 12 or 13
  • intervention/image 4 with the GD extension
  • league/flysystem-aws-s3-v3 if browsers should upload straight to S3
  • A queue worker, for the variant job

Install

composer require mohmmadshabrani/laravel-image-engine
php artisan vendor:publish --tag=image-engine-config
php artisan vendor:publish --tag=image-engine-migrations
php artisan migrate

The migration creates one table, media (change the name with image-engine.table before you migrate).

1. Say where images are taken

Each place in your product that takes images is a purpose. List them in a string-backed enum:

namespace App\Enums;

use Shabrani\ImageEngine\Contracts\Purpose;
use Shabrani\ImageEngine\Enums\MediaType;
use Shabrani\ImageEngine\Support\MediaPolicy;
use Shabrani\ImageEngine\Support\MediaVariant;

enum ImagePurpose: string implements Purpose
{
    case ListingPhoto = 'listing_photo';

    public function policy(): MediaPolicy
    {
        return match ($this) {
            self::ListingPhoto => new MediaPolicy(
                uploadPermission: 'listings.photos.add', // checked with $user->can()
                types: [MediaType::Jpeg, MediaType::Png, MediaType::Webp],
                maxBytes: 25 * 1024 * 1024,
                maxPerOwner: 20,
                disk: 's3',
                directory: 'media/listing-photos',
                clientMaxEdge: 1600, // the browser shrinks larger images first; null sends them as they are
                variants: [
                    new MediaVariant('thumb', 320),
                    new MediaVariant('display', 1600, quality: 82, watermark: true),
                ],
            ),
        };
    }
}

Then name the enum in config/image-engine.php:

'purposes' => App\Enums\ImagePurpose::class,

uploadPermission is any ability $user->can() understands: a Gate, a policy ability or a spatie/laravel-permission permission.

2. Routes

The package registers two groups. Change their prefix and middleware in image-engine.routes, or set a group to null and load routes/session.php or routes/token.php from the package yourself.

Session routes (default prefix api/media, middleware web, auth):

Route What it does Who
GET /policies The upload rules of every purpose the user may upload to Signed-in user
POST / Checks the file and returns the upload plan: signed part URLs and a media token. The same client_key always returns the same upload The purpose's uploadPermission
GET /{media} One upload Its uploader
DELETE /{media} Cancels an upload that is not claimed yet Its uploader

Token routes (default prefix api/media-uploads, middleware throttle:600,1). They take no session or CSRF token, only the X-Media-Token header for that one upload, so a service worker can use them:

Route What it does
GET /{media}/parts Parts already stored, and fresh URLs for the missing ones
POST /{media}/complete Joins the parts and verifies the stored object. Safe to call again. Answers 409 with missing_parts when parts are missing
PUT /{media}/parts/{part} Receives one part when the disk is not S3 (signed URL)

A media row moves through these statuses: pending → uploaded (verified) → ready (variants made). A file that fails a check is deleted and marked rejected with a reason. If the variant job keeps failing, the original is kept and the row is failed.

3. The browser

The browser code ships in this repository as TypeScript source. Install it from GitHub and let your bundler compile it (Vite does this out of the box):

yarn add @mohmmadshabrani/laravel-image-engine@github:Mohmmadshabrani/laravel-image-engine#v1.0.0

Keep the tag in step with the Composer version.

React

import { MediaUploadProvider, useMediaUploads } from '@mohmmadshabrani/laravel-image-engine/react';

// Once, near the root of the app:
<MediaUploadProvider workerUrl="/upload-worker.js">
  <App />
</MediaUploadProvider>;

function ListingPhotos({ listingId }: { listingId: number }) {
  const uploads = useMediaUploads({
    purpose: 'listing_photo',
    scope: `listing:${listingId}`,
    label: `Listing #${listingId}`,
  });

  return (
    <>
      <input type="file" multiple accept="image/*" onChange={(event) => uploads.add([...(event.target.files ?? [])])} />
      {uploads.items.map((item) => (
        <p key={item.clientKey}>
          {item.fileName}: {item.state} {Math.round(item.progress * 100)}% {item.error}
        </p>
      ))}
      <button disabled={uploads.pendingCount > 0} onClick={() => save(listingId, uploads.readyIds).then(uploads.forgetSaved)}>
        Save
      </button>
    </>
  );
}

useMediaUploadQueue() returns every item in the queue, for an app-wide upload tray.

By default the queue calls the session routes with fetch and Laravel's XSRF-TOKEN cookie. To use your own HTTP client, other URLs or another IndexedDB name, build the engine yourself and pass it to the provider:

import { createPageUploadEngine } from '@mohmmadshabrani/laravel-image-engine';

const engine = createPageUploadEngine({
  session: { loadPolicies, start, cancel }, // start must reject with UploadHttpError
  tokenUrl: '/api/media-uploads',
  databaseName: 'my-app-uploads',
});

Without React

createPageUploadEngine() returns a MediaUploadEngine. Call restore() once, add(files, { purpose, scope, label }) to queue files, and read the queue with subscribe(listener) and getSnapshot().

Finishing uploads after the page closes

Create a service worker file, build it as one file at your site root, and pass its URL to the provider as workerUrl:

// upload-worker.ts
import { installUploadWorker } from '@mohmmadshabrani/laravel-image-engine/worker';

installUploadWorker();

On a Background Sync the worker finishes uploads that already have a media token. It has no fetch handler, so it never touches page requests. Browsers without Background Sync (iOS) resume when the page opens again.

4. Attach uploads to a record

The screen sends the media ids with its own save. Claim them inside that save's transaction:

use Shabrani\ImageEngine\Support\ClaimMedia;

DB::transaction(function () use ($request, $listing) {
    $listing->update($request->safe()->except('media_ids'));

    app(ClaimMedia::class)->claim($listing, ImagePurpose::ListingPhoto, $request->validated('media_ids'), $request->user());
});

claim() throws a ValidationException on the media_ids field when a file is missing, unfinished, uploaded by someone else, meant for another purpose, already attached, or over the purpose's maxPerOwner.

Read a record's images and their URLs:

use Shabrani\ImageEngine\Models\Media;
use Shabrani\ImageEngine\Support\MediaUrls;

$photos = Media::query()->whereMorphedTo('owner', $listing)->orderBy('position')->get();

app(MediaUrls::class)->variants($photos->first()); // ['thumb' => ['url' => ..., 'width' => 320, 'height' => 240], ...]

URLs are plain on disks with 'visibility' => 'public' and signed for one hour on every other disk.

Remove an image with DeleteMedia, not $media->delete() alone. It deletes the row now and the files after the transaction commits, so a rolled-back save never leaves a row without its files:

app(\Shabrani\ImageEngine\Support\DeleteMedia::class)->delete($media);

5. Clean up

Schedule the prune command. It deletes uploads that are still pending or unclaimed after image-engine.unclaimed_hours (24), with their files, and aborts abandoned S3 multipart uploads:

Schedule::command('media:prune')->daily();

S3 setup

  • CORS on the bucket: allow PUT from your site's origin, with the request headers content-type and x-amz-checksum-sha256. No response headers need exposing.
  • Add a lifecycle rule that aborts incomplete multipart uploads after one day, as a backup for media:prune.

Local development and tests

Set IMAGE_ENGINE_DISK to a local disk and every purpose stores there, with the parts going through Laravel. A disk that is served through signed URLs works well:

// config/filesystems.php
'media-local' => [
    'driver' => 'local',
    'root' => storage_path('app/media'),
    'serve' => true,
    'url' => env('APP_URL').'/media-files',
],

In PHPUnit, Storage::fake() the purpose's disk and the local disk, and run the queue with the sync driver.

Configuration

Key Default Meaning
purposes null Your purpose enum
table media Table name
disk IMAGE_ENGINE_DISK Replaces every purpose's disk when set
upload_target auto auto: signed URLs on S3 disks, through Laravel otherwise. proxy: always through Laravel
parts_disk local Where parts wait when they go through Laravel
part_size 5 MiB S3's minimum multipart part size
header_bytes 4096 Bytes of the file sent with the start call for the magic-byte check
signed_url_minutes 15 Lifetime of a part URL
token_minutes 360 Lifetime of a media token
unclaimed_hours 24 Age at which media:prune deletes an unclaimed upload
watermark no image path, position and offset of the image stamped on variants declared with watermark: true
routes see above Prefix and middleware of the two route groups

Testing

composer test   # PHPUnit
yarn test       # Vitest
yarn typecheck

License

MIT. See LICENSE.