Skip to content

Instantly share code, notes, and snippets.

@rummykhan
Last active April 8, 2021 20:35
Show Gist options
  • Save rummykhan/a0a31eee84d1e0393dfc2f8a700a03f6 to your computer and use it in GitHub Desktop.
Save rummykhan/a0a31eee84d1e0393dfc2f8a700a03f6 to your computer and use it in GitHub Desktop.
Generic Image Aware Trait
<?php
namespace App\Models\ImageAware;
use Illuminate\Http\UploadedFile;
trait ImageAwareTrait
{
/**
* Save image and get image name
*
* @param UploadedFile $file
* @param string $attribute
* @param string $disk
*
* @return string
*/
public function saveImage($file, $attribute = 'image', $disk = 'local') : string
{
$filePath = $this->getFilePath($attribute);
return $file->store($filePath, $disk);
}
/**
* Get image url
*
* @param string $attribute
* @param string $disk
* @param string $default
*
* @return string
*/
public function getImageUrl($attribute = 'image', $default = null) : string
{
if (empty($attribute)) {
return $default;
}
$filePath = $this->getFilePath($attribute);
$fileName = $this->{$attribute};
if (empty($fileName)) {
return $default;
}
return asset($filePath . '/' . $fileName);
}
/**
* Get file path from image to directory map
*
* @param $attribute
* @return string|mixed
*/
protected function getAttributeDirectory($attribute): ?string
{
if (!property_exists($this, 'imageAttributeToDirectoryMap')) {
return null;
}
return $this->imageAttributeToDirectoryMap[$attribute];
}
/**
* Get attribute to file path
*
* @param $attribute
* @return mixed|string|null
*/
public function getFilePath($attribute): ?string
{
return $this->getAttributeDirectory($attribute);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment