This is a Laravel Eloquent trait that provides an easy and dynamic way to manage photos in your Eloquent models.
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
];
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;
composer test
The MIT License (MIT). Please see License File for more information.