I have a dynamic action class that is reusable through the entire app UploadImageAction
It handles single image upload per request:
class UploadImageAction implements UploadImageContract
{
public function handle(Request $request, $imageProperty, $image, $imageDir)
{
if ($request->hasFile($imageProperty)) {
// Handle uploading lf_image
if (!is_null($image) && Storage::exists($image)) {
// Throw exceptions here
Storage::delete($image);
}
// Throw exceptions here
return $request->file($imageProperty)->store($imageDir);
}
}
}
The way I handle the action is by creating a method in service class:
protected function handleAttachments($request, $report)
{
// Handle Attachments
$uploadImageAction = resolve(UploadImageAction::class);
// Handle lf_image action
if($request->hasFile('attachments')) {
$report->attachments = $uploadImageAction->handle($request, 'attachments', $report->attachments, 'incidents');
}
return $report;
}
Then call in within the storeReport():
$report = Report::create($request->validated());
$report = $this->handleAttachments($request, $report); // Called here
What I’m trying to do is make it possible to upload multiple images, I wrote the below code block in the storeReport method in Service class just to test (commented out the handleAttachments()):
$ir_counter = $report->ir_number->prefix ?? 'IR#' . str_pad($report->ir_number, 4, '0', STR_PAD_LEFT);
$attachments = [];
if($request->hasfile('attachments'))
{
foreach($request->file('attachments') as $attachment)
{
$name = time().rand(100, 1000) . '.' . $attachment->extension();
$attachment->move(public_path('app/incident/' . $ir_counter . '/'), $name);
$attachments[] = $name;
}
}
$report->attachments = implode('|', $attachments);
It’s working as expected. But how can I reflect the array/loop in the UploadImageAction code? When I try to do so, the DB column of attachments shows: [{}].