PHPackages                             oi-lab/oi-laravel-attachments - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Image &amp; Media](/categories/media)
4. /
5. oi-lab/oi-laravel-attachments

ActiveLibrary[Image &amp; Media](/categories/media)

oi-lab/oi-laravel-attachments
=============================

Polymorphic file attachments, files and folders for Laravel applications

v1.0.4(2w ago)0234↑33.3%2MITPHPPHP ^8.2

Since Jun 14Pushed 2w agoCompare

[ Source](https://github.com/oi-lab/oi-laravel-attachments)[ Packagist](https://packagist.org/packages/oi-lab/oi-laravel-attachments)[ RSS](/packages/oi-lab-oi-laravel-attachments/feed)WikiDiscussions main Synced 1w ago

READMEChangelogDependencies (19)Versions (5)Used By (2)

[![OI Laravel TypeScript Generator](./assets/github-preview.png)](./assets/github-preview.png)

OI Laravel Attachments BETA
===========================

[](#oi-laravel-attachments-beta)

[![Latest Version on Packagist](https://camo.githubusercontent.com/ec95b227149b534604bdcc2b476b94d7fb40c0e68813b20946c93672c05126a1/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6f692d6c61622f6f692d6c61726176656c2d6174746163686d656e74732e737667)](https://packagist.org/packages/oi-lab/oi-laravel-attachments)[![Total Downloads](https://camo.githubusercontent.com/717b89e8d890466d82daffe1e62f6db24d037f1b5ee89fa32ec159920f31f871/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6f692d6c61622f6f692d6c61726176656c2d6174746163686d656e74732e737667)](https://packagist.org/packages/oi-lab/oi-laravel-attachments)[![Tests](https://camo.githubusercontent.com/4d3d7c7e8aa3f9342dc802777a53a288c6f84a330ff43920dab70dbb1cf56ab6/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6f692d6c61622f6f692d6c61726176656c2d6174746163686d656e74732f74657374732e796d6c3f6c6162656c3d7465737473)](https://github.com/oi-lab/oi-laravel-attachments/actions)[![License](https://camo.githubusercontent.com/9c14de4affa42159bd5f8462a91f4759dcda4398dc174108c1bb2b82cc0bd96e/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f6f692d6c61622f6f692d6c61726176656c2d6174746163686d656e7473)](LICENSE)

A Laravel package for polymorphic file attachments. Attach files to **any** Eloquent model, organize them into named collections with ordering, store rich file metadata (EXIF, IPTC, dimensions, color profile), and group files into nested folders.

Features
--------

[](#features)

- **Polymorphic Attachments**: Attach files to any model via a single `HasAttachments` trait
- **Named Collections**: Group attachments per model (e.g. `gallery`, `cover`, `documents`)
- **Ordering**: First-class sort support with reorder, move, and swap helpers
- **Rich File Metadata**: `File` model captures mimetype, filesize, dimensions, MD5, EXIF, IPTC, and color info
- **Folders**: Optional self-nesting folder tree for organizing files
- **Upload Actions**: Single-call actions to store uploads and attach them to a model
- **Audit Tracking**: Automatic `created_by` / `updated_by` tracking on every record
- **Configurable Models**: Swap in your own `File`, `Folder`, or `Attachment` subclasses
- **Storage Agnostic**: Works with any Flysystem disk (local, S3, etc.)

How It Works
------------

[](#how-it-works)

The package revolves around three models:

- **File** — a stored file and its metadata, optionally living inside a `Folder`.
- **Folder** — a self-nesting container (`parent_id` tree) for organizing files.
- **Attachment** — a polymorphic pivot linking a `File` to any `attachable` model, with a `collection` name and `sort` order.

Host models opt in with the `HasAttachments` trait, which exposes the full attach / detach / sync / reorder API. All package internals resolve model classes through the `OiLaravelAttachments` resolver, so you can override any model from config without touching package code.

Requirements
------------

[](#requirements)

- PHP 8.2+
- Laravel 11.0+, 12.0+, or 13.0+

Installation
------------

[](#installation)

```
composer require oi-lab/oi-laravel-attachments
```

The package auto-discovers and registers its service provider — no manual registration required.

### Local Development

[](#local-development)

For local development, add this to your main project's `composer.json`:

```
{
    "repositories": [
        {
            "type": "path",
            "url": "./packages/oi-lab/oi-laravel-attachments"
        }
    ]
}
```

Then:

```
composer require oi-lab/oi-laravel-attachments
```

### Publish &amp; Migrate

[](#publish--migrate)

Publish the migrations (and optionally the config) and run them:

```
php artisan vendor:publish --tag=oi-laravel-attachments-migrations
php artisan vendor:publish --tag=oi-laravel-attachments-config
php artisan migrate
```

This creates the `folders`, `files`, and `attachments` tables.

Configuration
-------------

[](#configuration)

The config file `config/oi-laravel-attachments.php` exposes the following options:

```
return [
    // Model used for the created_by / updated_by audit relationships
    'user_model' => 'App\Models\User',

    // Model classes used by the package — override with your own subclasses
    'models' => [
        'file' => OiLab\OiLaravelAttachments\Models\File::class,
        'folder' => OiLab\OiLaravelAttachments\Models\Folder::class,
        'attachment' => OiLab\OiLaravelAttachments\Models\Attachment::class,
    ],

    // Disk used to store uploaded files (defaults to ATTACHMENTS_DISK, then FILESYSTEM_DISK)
    'disk' => env('ATTACHMENTS_DISK', env('FILESYSTEM_DISK', 'local')),

    // Directory uploaded files are stored under
    'directory' => 'uploads',
];
```

Usage
-----

[](#usage)

### Make a Model Attachable

[](#make-a-model-attachable)

Add the `HasAttachments` trait to any model:

```
use Illuminate\Database\Eloquent\Model;
use OiLab\OiLaravelAttachments\Concerns\HasAttachments;

class Product extends Model
{
    use HasAttachments;
}
```

### Attach &amp; Detach Files

[](#attach--detach-files)

```
// Attach a File (model instance or id) to a collection
$product->attachFile($file, collection: 'gallery');

// Detach
$product->detachFile($file, 'gallery');

// Read attachments (ordered by sort)
$product->attachments;                    // all attachments
$product->attachments('gallery')->get();  // one collection
$product->singleAttachment('cover');      // MorphOne for single-file collections

// Read the underlying File models directly
$product->attached_files;                 // Collection
```

### Sync a Collection

[](#sync-a-collection)

`syncAttachments()` replaces every attachment in a collection. `syncAttachmentsIfChanged()` does the same but skips the database work when the ids and their order already match:

```
$product->syncAttachments([$id1, $id2, $id3], 'gallery');

// Returns false and does nothing if the collection is already in this exact state
$changed = $product->syncAttachmentsIfChanged([$id1, $id2, $id3], 'gallery');
```

### Reorder

[](#reorder)

```
// Map file ids to their new sort position
$product->reorderAttachments([
    $fileA->id => 0,
    $fileB->id => 1,
    $fileC->id => 2,
], 'gallery');
```

### Uploading Files

[](#uploading-files)

Use the action classes instead of building `File` records manually. `StoreUploadedFile` persists the upload and captures its metadata; `AttachUploadedFiles` stores many uploads and attaches them in a single call:

```
use OiLab\OiLaravelAttachments\Actions\StoreUploadedFile;
use OiLab\OiLaravelAttachments\Actions\AttachUploadedFiles;

public function store(Request $request, Product $product): RedirectResponse
{
    // Store a single upload, get back a File model
    $file = StoreUploadedFile::handle($request->file('document'));

    // Store multiple uploads and attach them to the product
    AttachUploadedFiles::handle($product, $request->file('images'), 'gallery');

    return back();
}
```

### Working with Files

[](#working-with-files)

The `File` model offers type helpers, storage access, and a search scope:

```
$file->isImage();   // mimetype starts with image/
$file->isVideo();
$file->isAudio();

$file->getFullPath();  // absolute path (local disks only)
$file->getStream();    // stream resource (works with S3 etc.)

File::search('invoice')->get(); // matches filename, title, or description
```

File metadata is exposed as a value object rather than raw JSON:

```
$file->metadata->width;
$file->metadata->height;
$file->metadata->aspect_ratio;
$file->metadata->exif;        // ExifValueObject|null
$file->metadata->iptc;        // IptcValueObject|null
$file->metadata->resolution;  // ResolutionValueObject|null
```

### Folders

[](#folders)

Files can optionally be organized into a nested folder tree:

```
$folder = Folder::create(['name' => 'Invoices']);
$child = Folder::create(['name' => '2026', 'parent_id' => $folder->id]);

$folder->children;  // HasMany
$folder->files;     // HasMany
$child->parent;     // BelongsTo
```

Customizing Models
------------------

[](#customizing-models)

To extend a model, subclass the package model and point the config at your class. Always resolve model classes through the `OiLaravelAttachments` helper so your override is respected everywhere:

```
use OiLab\OiLaravelAttachments\Models\File as BaseFile;

class File extends BaseFile
{
    // your customizations
}
```

```
// config/oi-laravel-attachments.php
'models' => [
    'file' => App\Models\File::class,
],
```

Events
------

[](#events)

Each action dispatches a Laravel event you can listen to. All events live in `OiLab\OiLaravelAttachments\Events`:

EventDispatched when`FileStored`An uploaded file is stored by `StoreUploadedFile``FileAttached`A file is attached to a model`FileDetached`One or more attachments are removed`AttachmentsSynced`A collection is replaced via `syncAttachments()``AttachmentsReordered`Attachments are reordered`AttachmentCreated` / `AttachmentUpdated` / `AttachmentDeleted`Model-level attachment lifecycle`FileCreated` / `FileUpdated` / `FileDeleted`A file record is created, updated, or soft deleted`FileMoved`A file is moved to a different folder`FileRestored`A soft-deleted file is restored`FolderCreated` / `FolderUpdated` / `FolderDeleted`A folder is created, updated, or soft deleted`FolderMoved`A folder is moved to a different parent`FolderRestored`A soft-deleted folder is restored```
use Illuminate\Support\Facades\Event;
use OiLab\OiLaravelAttachments\Events\FileStored;

Event::listen(function (FileStored $event) {
    if ($event->file->isImage()) {
        // generate thumbnails, optimize, ...
    }
});
```

See the [Events documentation](docs/advanced/events.md) for each event's payload and dispatch behaviour.

Database Schema
---------------

[](#database-schema)

TablePurpose`folders`Self-nesting folder tree (`parent_id`), soft-deletable`files`Stored files with metadata, optional `folder_id`, soft-deletable`attachments`Polymorphic pivot (`attachable`, `file_id`, `collection`, `sort`)All three tables carry a unique `uuid`, `created_by` / `updated_by` audit columns, and timestamps.

Testing
-------

[](#testing)

This package ships **75 tests** covering the attachment trait, models and relationships, sorting, upload actions, file metadata, audit tracking, and events.

```
# Run all tests
vendor/bin/pest

# Run a specific suite
vendor/bin/pest tests/Unit
vendor/bin/pest tests/Feature

# With coverage
vendor/bin/pest --coverage
```

AI Assistant Skills
-------------------

[](#ai-assistant-skills)

This package ships a skill file that gives AI coding assistants (Claude Code, JetBrains Junie) context about how attachments work. Install it into your application with the Artisan command:

```
php artisan oi:skills
```

This writes `.claude/skills/oilab-laravel-attachments/SKILL.md` and `.junie/skills/oilab-laravel-attachments/SKILL.md`, and adds an `oi-lab/oi-laravel-attachments` rules section to your project's `CLAUDE.md`. See the [documentation](docs/advanced/skills.md) for details.

Contributing
------------

[](#contributing)

Contributions are welcome! When contributing:

1. Write tests for new features
2. Ensure all tests pass: `vendor/bin/pest`
3. Run `vendor/bin/pint` to match the project code style
4. Update documentation as needed

License
-------

[](#license)

This package is open-source software licensed under the [MIT license](LICENSE).

Credits
-------

[](#credits)

**[Olivier Lacombe](https://www.olacombe.com)** - Creator and maintainer

Olivier is a Product &amp; Technology Director based in Montpellier, France, with over 20 years of experience innovating in UX/UI and emerging technologies. He specializes in guiding enterprises toward cutting-edge digital solutions, combining user-centered design with continuous optimization and artificial intelligence integration.

**Projects &amp; Resources:**

- [OI Dev Docs](https://dev.olacombe.com) - Documentation for all Open Source OI Lab packages
- [OnAI](https://onai.olacombe.com) - Training courses and masterclasses on generative AI for businesses
- [Promptr](https://promptr.olacombe.com) - Prompt engineering Management Platform

Support
-------

[](#support)

For support, please open an issue on the [GitHub repository](https://github.com/oi-lab/oi-laravel-attachments/issues).

###  Health Score

45

—

FairBetter than 91% of packages

Maintenance96

Actively maintained with recent releases

Popularity16

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~8 days

Total

4

Last Release

20d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/369876?v=4)[Olivier Lacombe](/maintainers/olacombe)[@olacombe](https://github.com/olacombe)

---

Top Contributors

[![olacombe](https://avatars.githubusercontent.com/u/369876?v=4)](https://github.com/olacombe "olacombe (8 commits)")

---

Tags

attachmentlaravelpackagepolymorphiclaravelfilesmediaattachmentsuploadspolymorphicfolders

###  Code Quality

TestsPest

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/oi-lab-oi-laravel-attachments/health.svg)

```
[![Health](https://phpackages.com/badges/oi-lab-oi-laravel-attachments/health.svg)](https://phpackages.com/packages/oi-lab-oi-laravel-attachments)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3345.3M348](/packages/psalm-plugin-laravel)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9762.4M134](/packages/roots-acorn)[api-platform/laravel

API Platform support for Laravel

58174.6k17](/packages/api-platform-laravel)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

255.2k](/packages/aedart-athenaeum)[pressbooks/pressbooks

Pressbooks is an open source book publishing tool built on a WordPress multisite platform. Pressbooks outputs books in multiple formats, including PDF, EPUB, web, and a variety of XML flavours, using a theming/templating system, driven by CSS.

45444.2k1](/packages/pressbooks-pressbooks)[simplestats-io/laravel-client

Server-side analytics for Laravel that follows the full funnel from visit to registration to payment, attributed to the channel that drove it. Revenue, MRR, churn and ad-spend profit (ROAS/CAC) per channel. GDPR compliant, ad-blocker proof.

5022.6k](/packages/simplestats-io-laravel-client)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
