deleting files from s3 using laravel 5.6

11,717

Solution 1

Its just like file deletion from disk. Check this to the laravel document: https://laravel.com/docs/5.6/filesystem#deleting-files

 $imageName = $studentPortfolios[$i]->portfolio_link; // this returns the file name stored in the DB
 \Storage::disk('s3')->delete('s3_folder_path/'. $imageName);

Make sure file has permision to delete. If not give the permission from s3 by selecting the file or directory and select Make Public option from action in s3.

Solution 2

I have done with this below code.

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

    $bucket  =  "bucket";
    $keyname = "keyname";
    $s3 = new S3Client([
    'version' => 'latest',
    'region'  => 'region'
    ]);
    $result = $s3->deleteObject(array(
        'Bucket' => $bucket,
        'Key'    => $keyname
    ));
Share:
11,717
Dhaval Chheda
Author by

Dhaval Chheda

I have been developing and architecting web based solutions for over 12 years. I have over a decade of real-world experience having worked on all levels of the SDLC ( interacting with the client to working with a fresher ), strong ethics, obsessed about code quality, never say die attitude, willingness to help peers and willingness to learn. I have been working remotely for over 5 years.

Updated on August 31, 2022

Comments

  • Dhaval Chheda
    Dhaval Chheda over 1 year

    I want to delete files from my bucket programmatically but it is not happening

    I have the below code

    $s3 = \Storage::disk('s3');
    $existingImagePath = $studentPortfolios[$i]->portfolio_link; // this returns the path of the file stored in the db
    $s3->delete($existingImagePath);
    

    But this is not deleting the files from the bucket

    I have to write objects permission to the bucket for everyone for the time being as I am running this from my local setup.

    Please note:- I am able to upload files but deleting is not working

    Any advice on this will be really helpful.

    • Tpojka
      Tpojka over 5 years
      Edit question with response object you are getting from S3. There is message about what happened.
    • Jignesh Joisar
      Jignesh Joisar over 5 years
      @Dhaval Chheda may be missing delete permission in bucket other wise your path is not proper but your code is right
    • Dhaval Chheda
      Dhaval Chheda over 5 years
      @Tpojka there is no message it just does not delete
    • Tpojka
      Tpojka over 5 years
      You should always get some response, wether there was an error wether there was successful action. Try with this package or set last line in try catch block.
    • Pawan Verma
      Pawan Verma about 4 years
      Here is the solution that works perfect for me Delete file from s3 bucket in laravel
  • Dhaval Chheda
    Dhaval Chheda over 5 years
    directly it works.. so there is something in the code but don't know what and how to fix it