Skip to content

Turn any field on your Eloquent models into attachments

License

Notifications You must be signed in to change notification settings

aniftyco/laravel-attachments

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

18 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Attachments for Laravel

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.

About

Turn any field on your Eloquent models into attachments

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Languages