mastercut/app/Traits/UploadAttachment.php

61 lines
2.3 KiB
PHP

<?php
namespace App\Traits;
use App\Models\Attachment;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
trait UploadAttachment
{
public function uploadAttachment(UploadedFile|string $file, string $path, string $classModel, string $featureId): void
{
DB::transaction(function () use ($file, $path, $classModel, $featureId) {
if (is_string($file) && strpos($file, 'data:image') === 0) {
$imageData = explode(',', $file)[1];
$image = base64_decode($imageData);
$extension = 'png';
$fileName = Str::uuid();
$fullFileName = $fileName.'.'.$extension;
$existingAttachment = Attachment::where('attachmentable_id', $featureId)
->where('attachmentable_type', $classModel)
->first();
if ($existingAttachment) {
if ($classModel !== 'App\\Models\\Attendance') {
$oldFilePath = $path.'/'.$existingAttachment->created_at->format('Y-m-d').'/'.$existingAttachment->name.'.'.$existingAttachment->extension;
Storage::disk('public')->delete($oldFilePath);
}
}
$date = now()->format('Y-m-d');
Storage::disk('public')->put($path.'/'.$date.'/'.$fullFileName, $image);
Attachment::create([
'attachmentable_id' => $featureId,
'attachmentable_type' => $classModel,
'name' => $fileName,
'extension' => $extension,
'size' => strlen($image),
]);
} elseif ($file instanceof UploadedFile) {
$date = now()->format('Y-m-d');
$extension = $file->getClientOriginalExtension();
$fileName = Str::uuid();
$file->storeAs($path.'/'.$date, $fileName.'.'.$extension, 'public');
Attachment::create([
'attachmentable_id' => $featureId,
'attachmentable_type' => $classModel,
'name' => $fileName,
'extension' => $extension,
'size' => $file->getSize(),
]);
}
});
}
}