Skip to content

Instantly share code, notes, and snippets.

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

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

Select an option

Save eduPHP/84bb126d3853e3a0a344948427dcd7a2 to your computer and use it in GitHub Desktop.
<?php
namespace App\Observers;
use Dotenv\Exception\InvalidFileException;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
class UploadedImagesObserver
{
public function saved(Model $model)
{
/**
* @var $image \Illuminate\Http\UploadedFile
*/
if (!$image = $model->getUploadedImage()) {
return $model;
}
if(is_array($image)){
return $this->storeMultiple($model, $image);
}
$filePath = $this->storeImage($model, $image);
$data = [
'name' => $image->getClientOriginalName(),
'mime' => $image->getClientMimeType(),
'path' => $filePath,
'size' => $image->getSize(),
];
if (!$model->image) {
$model->image()->create($data);
} else {
Storage::delete($model->image->path);
$model->image->update($data);
}
return $model;
}
/**
* @param \Illuminate\Database\Eloquent\Model $model
* @param $image
*
* @return mixed
*/
public function storeImage(Model $model, $image)
{
if ($image->getSize() > config('filesystems.max_filesize') * 1024) {
throw new InvalidFileException();
}
$diskName = Str::slug(Str::snake(get_class($model)), '_');
$path = "uploads/images/{$diskName}";
$filePath = $image->storeAs($path, $image->hashName());
return $filePath;
}
public function storeMultiple(Model $model, $image)
{
foreach ($image as $i => $img) {
$filePath = $this->storeImage($model, $img);
$data = [
'name' => $img->getClientOriginalName(),
'mime' => $img->getClientMimeType(),
'path' => $filePath,
'size' => $img->getSize(),
];
$model->image()->create($data);
}
return $model;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment