Turn any field on your Eloquent models into attachments
Warning
This package is not ready for general consumption
You can install the package via Composer:
composer require aniftyco/laravel-attachments:dev-master
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();
});
}
};
To add attachments to your Eloquent models, use the provided cast classes.
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();
// ...
}
}
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();
// ...
}
}
Thank you for considering contributing to the Attachments for Laravel package! You can read the contribution guide here.
The MIT License (MIT). Please see License File for more information.