lundi 23 juillet 2018

File does not exist in S3 using Laravel even though it is there

I am building a website and I'm uploading some image files to S3 and then I am trying to delete the same files but for some reason Laravel doesn't find the file even though I've triple checked that the file is there in S3.

Here is the code that I'm using:

<?php

namespace App\Logic;

use App\UrlRequest;
use Exception;
use Illuminate\Support\Facades\Storage;

class OldRequests {

    /**
     * Gets all requests older than 1 day and deletes the corresponding image
     * in s3 if it has not been already deleted
     */
    static function ifOlderThan1DaysDeleteImage()
    {
        $now = time();
        $time1DaysAgo = $now - (1*24*60*60);
        $datetime1DaysAgo = date('Y-m-d H:i:s', $time1DaysAgo);

        $notDeletedYet = UrlRequest::where('image_deleted', '=', 0)
            ->where('created_at', '<', $datetime1DaysAgo)
            ->get();

        foreach ($notDeletedYet as $request)
        {
            if ( ! Storage::disk('s3')->exists('screenshots/153228343051117.png'))
            {
                throw new Exception('Image file not found in S3.');
            }

            $result = Storage::disk('s3')->delete('screenshots/153228343051117.png');

            if ($result);
            {
                $request->image_deleted = 1;
                $request->save();
            }
        }
    }
}

The above code throws the exception: Image file not found in S3.

Note that the file name is hard-coded in though usually it comes from the $request variable which is an instance of the UrlRequest model.

I have no idea how to proceed with this so any help is much appreciated!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire