0

I'm working with Laravel v10, and I wanted to upload a picture into the directory public/frontend/images/home, so at the Controller, I tried this:

public function submitHomeBoxes(Request $request)
{
    try {
        $pageImage = Page::where('pag_type', 'home');
        if ($request->hasFile('box_image_1')) {
            $boxImage = $request->file('box_image_1');
            $imageName = $boxImage->getClientOriginalName();
            $imagePath = $boxImage->storeAs('public/frontend/images/home');
            $pageImage->where('pag_name', 'box_image_1')->update(['pag_value' => $imageName]);
            dd($imagePath); // returns false
        }

        return redirect()->back()->withSuccess('Image Uploaded');
    } catch (Exception $e) {
        dd($e);
    }
}

But it does not upload the picture somehow, and dd($imagePath) returns false!

So what's going wrong here? How can I solve this issue?


UPDATE:

I made some changes on the method to get the error, but still do not know what the error is:

try{
            $pageImage = Page::where('pag_type', 'home');
            if ($request->hasFile('box_image_1')) {
                $boxImage = $request->file('box_image_1');
                $imageName = $boxImage->getClientOriginalName();
                $imagePath = $boxImage->storeAs('public/frontend/images/home');
                if ($imagePath === false) {
                    $error = $boxImage->getError();
                    dd($error); //returns 0
        
                }
                $pageImage->where('pag_name', 'box_image_1')->update(['pag_value' => $imageName]);
                // dd($imagePath); return false
            }

        }catch (Exception $e) {
            dd($boxImage->getErrorMessage());
        }
japose7523
  • 29
  • 2
  • 15

1 Answers1

0

The storeAs() method requires two parameters. The directory where the file should be stored and the desired file name.

$imagePath = $boxImage->storeAs('public/frontend/images/home', $imageName);

public function submitHomeBoxes(Request $request)
{
    try {
        $pageImage = Page::where('pag_type', 'home');
        if ($request->hasFile('box_image_1')) {
            $boxImage = $request->file('box_image_1');
            $imageName = $boxImage->getClientOriginalName();
            $imagePath = $boxImage->storeAs('public/frontend/images/home', $imageName);
            if ($boxImage->getError() !== UPLOAD_ERR_OK) {
                dd($boxImage->getErrorMessage());
            }
            $pageImage->where('pag_name', 'box_image_1')->update(['pag_value' => $imageName]);
        }

        return redirect()->back()->withSuccess('Image Uploaded');
    } catch (Exception $e) {
        dd($e);
    }
}
Karl Hill
  • 12,937
  • 5
  • 58
  • 95