File exist but laravel can't find it (FileNotFoundException)

Viewed 790

I'm trying to check if the file exists to delete it when the post is deleted but it's never finding it.

If I change the Storage::exists() for Storage::get() just to check, I get the File Not Found Exception with the path C:/xampp/htdocs/cms/blog/public/images/apple.jpg which I can see the picture if I put in the browser.

Store function on PostController

public function store(CreatePostRequest $request)
{
    $input = $request->all();

    if ($file = $request->file('file')) {
        //
        $name = $file->getClientOriginalName();
        $file->move(public_path('images/'), $name);
        $input['path'] = $name;
    }

    $new_post = Post::create($input);
    return redirect(route('post.show', $new_post->id));
}

Destroy function on PostController

public function destroy($id)
{
    $post = Post::findOrFail($id);

    if (Storage::exists(public_path('images/') . $post->path))
        Storage::delete(public_path('images/') . $post->path);

    $post->delete();

    return redirect(route('posts.index'));
}

I also have this on my filesystems.php

'links' => [
    public_path('storage') => storage_path('app/public'),
    public_path('images') => storage_path('app/images'),
],

I can easily show the image in blade with just src="{{'/images/' . $post->path}}"

2 Answers

You could try using unlink.

$image_path = $post->path;
unlink($image_path);

The second option is to use the File Facade.

use Illuminate\Support\Facades\File; 
$filename = $post->path;
File::delete($filename);

Make sure that the image path is correct.

I Had to use the Illuminate\Support\Facades\File sugested by Aless

Fixed destroy funcion on PostController

public function destroy($id)
{
    $post = Post::findOrFail($id);

    $imagePath = public_path('images/') . $post->path;

    if (File::isFile($imagePath))
        File::delete($imagePath);

    $post->delete();

    return redirect(route('posts.index'));
}
Related