fsdolphin
2 years ago

Uploading images to the `public` directory stops working after the first image is uploaded

Posted 2 years ago by fsdolphin

I'm trying to upload images to the publicfolder but for some reason it only works the first time I run my code, in other words as soon as the images folder is created inside the public directory it stops working and I get a Not Found message. The first image is uploaded and saved to the database, but again, it only works one time and if I delete the images folder it works again for another image and then stops working again.

Message

Not Found:

The requested resource /images was not found on this server.

FYI - This is what I see in the browser when I get the message http://localhost:8000/images

Here is the code I have...

Routes:

Route::post('images', '[email protected]');

Controller:

class ImageController extends Controller{
        public function store(){
            $file = request()->file('image');
            $fileName = str_replace(' ','', $file->getClientOriginalName());
            $file->move(public_path().'/images/', $fileName);

            // Save to database
            $image = new \App\Image();
            $image->imageName = $fileName;
            $image->save();

            return back();
        }
}

Form:

<body>

    <form method="POST" action="images" enctype="multipart/form-data">

        {{ csrf_field() }}

        <input type="file" name="image">

        <button type="submit">Save</button>

    </form>

</body>

The funny thing is that if I change my code to upload to the storage directory instead it works fine, but of course I want to upload to the public directory.

If I change...

$file->move(public_path().'/images/', $fileName);

to

$file->storeAs('images/', $fileName);

It works fine.

What am I doing wrong?

Please sign in or create an account to participate in this conversation.