Skip to content

Instantly share code, notes, and snippets.

@eduPHP
Created March 29, 2021 18:21
Show Gist options
  • Select an option

  • Save eduPHP/d7bb0e11f85c1934442bc6d58b8f22ef to your computer and use it in GitHub Desktop.

Select an option

Save eduPHP/d7bb0e11f85c1934442bc6d58b8f22ef to your computer and use it in GitHub Desktop.
<?php
namespace App;
use App\Observers\UploadedImagesObserver;
use Illuminate\Http\UploadedFile;
trait SavesImages
{
private $uploadedImage;
protected static function bootSavesImages()
{
self::observe(UploadedImagesObserver::class);
}
public function getUploadedImage()
{
return $this->uploadedImage;
}
public function setImageAttribute($image)
{
if(!is_array($image)){
$this->uploadedImage = $image instanceof UploadedFile ? $image : null;
}
else{
$this->uploadedImage = [];
foreach ($image as $i => $img) {
if($img instanceof UploadedFile)
array_push($this->uploadedImage, $img);
}
}
}
public function image()
{
return $this->morphOne(Image::class, 'imageable');
}
public function images()
{
return $this->morphMany(Image::class, 'imageable');
}
public function getImageUrlAttribute()
{
return optional($this->image)->url;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment