laravel-vue-file-share/app/Jobs/UploadToS3.php

62 lines
1.9 KiB
PHP

<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;
class UploadToS3 implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected File $file;
/**
* Create a new job instance.
*/
public function __construct(File $file)
{
$this->file = $file;
}
/**
* Execute the job.
*/
public function handle(): void
{
// get file from constructor
$file = $this->file;
// if the file has not been uploaded to S3
if (!$file->s3) {
$localPath = Storage::disk('local')->path($file->stored_at);
Log::debug("File at " . $localPath . " being uploaded to S3");
// upload file to S3
try {
// upload to S3 with the "stored_at" path. get file from 'local' disk at the "stored_at" path.
$stored = Storage::put($file->stored_at, Storage::disk('local')->get($file->stored_at));
// if storing is successful, change DB and output log message
if ($stored) {
Log::debug("File uploaded to S3");
$file->s3 = 1;
$file->saveQuietly();
}
// else file storing on S3 was not successful.
else {
Log::error("File upload to S3 was unsuccessful");
}
}
catch (\Exception $exception) {
Log::error($exception->getMessage());
}
}
// else do nothing
}
}