Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/aniftyco/laravel-attachments
Turn any field on your Eloquent models into attachments
https://github.com/aniftyco/laravel-attachments
Last synced: about 2 months ago
JSON representation
Turn any field on your Eloquent models into attachments
- Host: GitHub
- URL: https://github.com/aniftyco/laravel-attachments
- Owner: aniftyco
- License: mit
- Created: 2024-10-08T00:17:30.000Z (3 months ago)
- Default Branch: master
- Last Pushed: 2024-10-21T00:38:41.000Z (3 months ago)
- Last Synced: 2024-10-21T04:00:36.522Z (3 months ago)
- Language: PHP
- Homepage:
- Size: 65.4 KB
- Stars: 10
- Watchers: 2
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE.md
Awesome Lists containing this project
README
# 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:
```sh
composer require aniftyco/laravel-attachments:dev-master
```## Usage
### Migrations
Your migrations need to have a `Blueprint::jsonb()` column set on it.
```php
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:
```php
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:
```php
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:
```php
use NiftyCo\Attachments\Casts\AsAttachments;class Post extends Model
{
protected function casts(): array
{
return [
'images' => AsAttachments::class,
];
}
}
```To attach multiple attachments to your model:
```php
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](CONTRIBUTING.md).
## License
The MIT License (MIT). Please see [License File](LICENSE.md) for more information.