behzadsp / eloquent-dynamic-photos
A Laravel Eloquent trait for dynamically handling and managing photo storage with ease.
v1.4.2
2024-06-18 05:51 UTC
Requires
- php: >=7.4
- ext-gd: *
- illuminate/database: ^7.0|^8.0|^9.0|^10.0|^11.0
- illuminate/filesystem: ^7.0|^8.0|^9.0|^10.0|^11.0
- illuminate/support: ^7.0|^8.0|^9.0|^10.0|^11.0
- intervention/image: ^2.7
- nesbot/carbon: ^2.53
README
This is a Laravel Eloquent trait that provides an easy and dynamic way to manage photos in your Eloquent models.
Installation
You can install the package via composer:
composer require behzadsp/eloquent-dynamic-photos
You can publish the config file with:
php artisan vendor:publish --provider="Behzadsp\EloquentDynamicPhotos\Providers\EloquentDynamicPhotosServiceProvider"
This is the contents of the global configurations for uploading images.
<?php return [ 'disk' => 'public', // Disk to use for storing photos 'root_directory' => 'images', // Root directory for photos 'name_attribute' => 'slug', // Model attribute used for file name 'quality' => 50, // Quality for encoding the photos 'format' => 'webp', // Format of the stored photos 'slug_limit' => 240, // Name limit to save in database 'timestamp_format' => 'U', // U represents Unix timestamp ];
Usage
After installing the package, simply use the HasPhotos
trait in your Eloquent models:
use Behzadsp\EloquentDynamicPhotos\Traits\HasPhotos; class YourModel extends Model { use HasPhotos; // ... }
Of course, you can override certain config in individual model by declaring the corresponding method. Like below:
class User extends Model { use HasPhotos; protected function eloquentPhotoDisk() { return 'user-avatar'; } protected function eloquentPhotoFormat() { return 'png'; } protected function eloquentPhotoRootDirectory() { return 'images'; } protected function eloquentPhotoQuality() { return '50'; } protected function eloquentPhotoNameAttribute() { return 'slug'; } protected function eloquentPhotoSlugLimit() { return '240'; } protected function eloquentPhotoTimestampFormat() { return 'U'; } }
You can now use the methods provided by the trait in your models:
$model = YourModel::first(); // delete photo file only and not database column. $model->deletePhotoFile('photo_field'); // update photo file and save it to database column. $model->updatePhoto($photo, 'photo_field'); // get full photo path $model->getPhotoFullPath('photo_path'); // get photo directory path $model->getPhotoDirectoryPath(); // get photo URL $model->photo_field_url;
Testing
composer test
License
The MIT License (MIT). Please see License File for more information.