Daffa Raka Mahendra
Daffa Raka Mahendra

Reputation: 7

laravel how to delete file in storage when we delete data

I have some problem to delete file when some value deleted.

This is my delete function:

public function delete($id, Adopsi $adopsi)
{
    Storage::delete('post/adopsi/' . $adopsi->image_post_adps);
    $data = Adopsi::where('id', $id)->delete();

    if ($data) {
        return redirect()->route('adopsi.index')->with('success', 'Data telah dihapus');
    } else {
        return redirect()->route('adopsi.index')->with('error', 'Data gagal dihapus');

    }
}

This is how I store my image before:

$imageSize = $request->file('image_post_adps')->getSize();
$imageName = $request->file('image_post_adps')->getClientOriginalName();
$request->file('image_post_adps')->storeAs('public/post/adopsi', $imageName);

directory folder where is use to save:
storage/app/public/post/adopsi/..... (there's my file),

I've used Storage::delete() and unlink() but it still isn't working.

Upvotes: 0

Views: 3415

Answers (3)

Ahmed Tidjani
Ahmed Tidjani

Reputation: 21

The below worked for me

$destinationPath = storage_path() . '/app/public/images/products';

File::delete($destinationPath . '/' . $product->id . '.' . $fileExtension);

Upvotes: 0

Hedayatullah Sarwary
Hedayatullah Sarwary

Reputation: 2834

First, make sure the file exists by building the path:

First of all, add the File Facade at the top of the controller:

use Illuminate\Support\Facades\File;

You can use public_path() & storage_path():

$path = public_path('../storage/YOUR_FOLDER_NAME/YOUR_FILE_NAME');
if (!File::exists($path)) {
    File::delete(public_path('storage/YOUR_FOLDER_NAME/YOUR_FILE_NAME'));
}

$path = storage_path().'/app/public/post/adopsi/'.$db->image;
if(File::exists($path)) {
    File::delete($path);
}

Upvotes: 0

habeebdev
habeebdev

Reputation: 278

Your images are stored at 'public' disk path. But disk is not specified in delete()

Try

Storage::disk('public')->delete('post/adopsi/' . $adopsi->image_post_adps);

Upvotes: 1

Related Questions