Store uploaded attachments
MODIFY
app/Http/Controllers/AttachmentController.php
app/Http/Controllers/AttachmentController.php
@@ -4,6 +4,8 @@ namespace App\Http\Controllers;
use App\Repositories\AttachmentRepository;
use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Storage;
+use Illuminate\Support\Str;
class AttachmentController extends Controller
{
@@ -22,10 +24,13 @@ class AttachmentController extends Controller
'file' => 'required|mimes:jpeg,png,pdf'
]);
+ $fileName = Str::random(20) . '.' . $request->file('file')->extension();
+ $filePath = $request->file('file')->storeAs('attachments', $fileName);
+
$transactionType = $request->transaction_type;
$transactionId = $request->transaction_id;
- $this->attachmentRepository->create($transactionType, $transactionId);
+ $this->attachmentRepository->create($transactionType, $transactionId, $filePath);
return redirect('/' . $transactionType . 's/' . $transactionId);
}

MODIFY
app/Models/Attachment.php
app/Models/Attachment.php
@@ -4,6 +4,7 @@ namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
+use Illuminate\Support\Facades\Storage;
class Attachment extends Model
{
@@ -14,4 +15,18 @@ class Attachment extends Model
'transaction_id',
'file_path'
];
+
+ // Accessors
+ public function getFileB64Attribute()
+ {
+ $file = Storage::get($this->file_path);
+
+ if (!$file) {
+ return null;
+ }
+
+ $type = pathinfo($this->file_path, PATHINFO_EXTENSION);
+
+ return 'data:image/' . $type . ';base64,' . base64_encode($file);
+ }
}

MODIFY
app/Repositories/AttachmentRepository.php
app/Repositories/AttachmentRepository.php
@@ -7,7 +7,7 @@ use Exception;
class AttachmentRepository
{
- public function create(string $transactionType, int $transactionId): Attachment
+ public function create(string $transactionType, int $transactionId, string $filePath): Attachment
{
if ($transactionType !== 'earning' && $transactionType !== 'spending') {
throw new Exception('Invalid transaction type ("' . $transactionType . '")');
@@ -16,7 +16,7 @@ class AttachmentRepository
return Attachment::create([
'transaction_type' => $transactionType,
'transaction_id' => $transactionId,
- 'file_path' => 'https://via.placeholder.com/500'
+ 'file_path' => $filePath
]);
}
}

MODIFY
resources/views/partials/attachments.blade.php
resources/views/partials/attachments.blade.php
@endif
@foreach ($payload->attachments as $attachment)
<div class="box__section">
- <img src="{{ $attachment->file_path }}" style="max-width: 100%; max-height: 200px; border-radius: 5px; vertical-align: top;" />
+ <img src="{{ $attachment->file_b64 }}" style="max-width: 100%; max-height: 200px; border-radius: 5px; vertical-align: top;" />
</div>
@endforeach
</div>

Store uploaded attachments