aniftyco/laravel-attachments

Turn any field on your Eloquent models into attachments

dev-master 2024-10-21 00:38 UTC

This package is auto-updated.

Last update: 2024-12-21 00:59:14 UTC


README

Turn any field on your Eloquent models into attachments

Warning

This package is not ready for general consumption

Installation

You can install the package via Composer:

composer require aniftyco/laravel-attachments:dev-master

Usage

Migrations

Your migrations need to have a Blueprint::jsonb() column set on it.

return new class extends Migration {
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();

            //...

            $table->jsonb('avatar')->nullable();
        });
    }
};

Adding Attachments to Models

To add attachments to your Eloquent models, use the provided cast classes.

Single Attachment

Use the AsAttachment cast to handle a single attachment:

use NiftyCo\Attachments\Casts\AsAttachment;

class User extends Model
{
    protected function casts(): array
    {
        return [
            'avatar' => AsAttachment::class,
        ];
    }
}

To set an image as an attachment on your model:

use NiftyCo\Attachments\Attachment;

class UserController
{
    public function store(UserStoreRequest $request, User $user)
    {
        $user->avatar = Attachment::fromFile($request->file('avatar'), folder: 'avatars');

        $user->save();

        // ...
    }
}

Multiple Attachments

Use the AsAttachments cast to handle multiple attachments:

use NiftyCo\Attachments\Casts\AsAttachments;

class Post extends Model
{
    protected function casts(): array
    {
        return [
            'images' => AsAttachments::class,
        ];
    }
}

To attach multiple attachments to your model:

class PostController
{
    public function store(PostStoreRequest $request, Post $post)
    {

        $images = $request->file('images');

        // Loop over all images uploaded and add to the
        // collection of images already on the post
        array_map(function($image) use ($post) {
            $post->images->addFromFile($image);
        }, $images);

        // Save post
        $post->save();

        // ...
    }
}

Contributing

Thank you for considering contributing to the Attachments for Laravel package! You can read the contribution guide here.

License

The MIT License (MIT). Please see License File for more information.