theUnforgiven's avatar

Storing on S3 using Dropzone

Hi all,

I'm trying to upload multiple images using Dropzone to then store the file name, year and location in my database, whilst also storing on my S3 account.

How I see it working is it will need to add images to the s3 bucket, in the year > location > img1.jpg format then if any other images are uploaded for the same year but a different location then this would be year > new_location > img2.jpg

So here's what I have already but the database only saves one record not 3 or 4 etc depending on how many images are uploaded, also it's not uploading the images to S3 either. The question is where am I going wrong??

$gallery = new Gallery;
if ($request->hasFile('file'))
{
    // retrieve file from request
    $files = $request->file('file');
    foreach ($files as $file) {

        // Check current year is same as inputted year
        $currentYear = date('Y');
        $year = $request->get('year');

        if($year == $currentYear) {
            $galleryYear = $year;
            $fileName = Str::random(25) . '.' . $file->getClientOriginalExtension();
            $filePath = $galleryYear . '/' . strtolower($request->location) . '/' . $fileName;

            // store on aws
            if (Storage::disk('s3')->putFileAs($filePath, $file, $fileName)) {
                // save
                $gallery->payload  = $filePath . $fileName;
                $gallery->update();
            } else {
                // throw exception
                Throw new Exception();
            }
        }
        // Save to local db
        $gallery->year = $request->year;
        $gallery->location = strtolower($request->location);
        $gallery->payload = $fileName;
    }
}
$gallery->save();

Can anyone advise me where I'm going wrong....

0 likes
7 replies
Swaz's avatar

@theUnforgiven Try moving $gallery->save(); into the foreach loop, looks like the values are being overwritten on each loop.

theUnforgiven's avatar

Also more so the uploading to S3 is also my issue, not uploading!!

theUnforgiven's avatar
theUnforgiven
OP
Best Answer
Level 51

I managed to achieve by the following:

if ($request->hasFile('file'))
            {
                // retrieve file from request
                $files = $request->file('file');
                foreach ($files as $file) {

                    $imageName = str_random(25).'.'.$file->getClientOriginalExtension();
                    $t = Storage::disk('s3')->put($imageName, file_get_contents($file), 'public');
                    $imageName = Storage::disk('s3')->url($imageName);

                    // Save to local db
                    $gallery = new Gallery;
                    $gallery->year = $request->year;
                    $gallery->location = strtolower($request->location);
                    $gallery->payload = $imageName;
                    $gallery->save();
                }
            }

Please or to participate in this conversation.