Khudadad's avatar

Can't delete image / file from public folder

I trying to delete a News from news table and it has an image field and the image is located in images/news directory in public folder after uploading, but the image itself is not deleted from that folder and only its path is deleted from database. any help the function:

public function destroy($id)
{
    $news = News::findOrFail($id);
    $image_path = app_path().'/images/news/'.$news->photo;
    //dd($image_path);
    if(File::exists($image_path))
    {
        File::delete($image_path);
        //unlink($image_path);
    }
    $news->delete();
    return redirect('admin/dashboard')->with('message','خبر موفقانه حذف شد');
}
0 likes
8 replies
joedawson's avatar

I think you're after the public_path() instead.

// Note removal of app_path()

$image_path = public_path().'/images/news/'.$news->photo;
Khudadad's avatar
Khudadad
OP
Best Answer
Level 2

Yes, I solved by changing like so:

public function destroy($id)
{
    $news = News::findOrFail($id);
    $image_path = public_path().'/'.$news->photo;
    unlink($image_path);
    $news->delete();
    return redirect('admin/dashboard')->with('message','خبر موفقانه حذف شد');
}

Thanks all for taking your time to reply.

1 like
richard's avatar

At some instance, the file you wish to delete might not exist in that folder. It is good to check first like this. Otherwise it will throw an error.

public function destroy($id)
{
        $news = News::findOrFail($id);
        $image_path = public_path().'/'.$news->photo;
        if(file_exists($image_path)) // check if the image indeed exists
        unlink($image_path);
    $news->delete();
        return redirect('admin/dashboard')->with('message','خبر موفقانه حذف شد');
}
3 likes
hemratna.bhimani@gmail.com's avatar

public function destroy(Request $request , $id) { $passport=Passport::find($id); $image_path = app_path().'/images/'.$passport->filename; if(file_exists($image_path)) unlink($image_path); $passport->delete(); return back()->with('success','Information has been deleted'); }

this my code for delete the user id but user id deleted iamge is not dleted in publick folder

LadyDeathKZN's avatar

Post may be old but has saved me 3 hours of frustration. Thank YOU!

1 like

Please or to participate in this conversation.