eggplantSword's avatar

Get Image File from public folder in backend

I'm trying to get an image from the public folder but I'm having issues where it always returns null.

This is my full code

 $filename = $id . '.png';
$fileDirectory = public_path('reportImages');
$fullFilepath = public_path('reportImages') . '/' . $filename;

			//create image
            $image = imagecreate(300, 200);

            $black = imagecolorallocate($image, 0, 0, 0);
            imagecolortransparent($image, $black);

            $red = imagecolorallocate($image, 255, 0, 0);

            imagerectangle($image, 5, 10, 195, 50, $red);

            File::ensureDirectoryExists($fileDirectory);

            imagepng($image, $fullFilepath);

            imagedestroy($image);

if I add dd(Storage::disk('public')->get('/reportImages/e96b4467-055d-4e5a-8c4e-bf2af6261177.png')) which is the real file name it returns null.

The full path for the file is /home/programador/code/btl-visor-new/public/reportImages/e96b4467-055d-4e5a-8c4e-bf2af6261177.png

What am I doing wrong? I'm trying to get the file to obtain the width and height of the image and finally I want to merge two images together.

0 likes
4 replies
jj15's avatar

I see you're using Storage::disk('public') which is different from the public folder in the root of your Laravel application, that's probably why you're getting null since it's not actually there. Storage::disk('public') stores its files in your-laravel-app/storage/app/public.

As a note, it's probably not the best idea to store any generated or uploaded files in the root public folder, since if you commit the project to a version control system like Git, they will persist there. The storage system is intended for those kinds of files.

1 like
eggplantSword's avatar

@jj15 I did have that in the public, but I've changed it now to save in the storage folder, however now when I try to get the image I get this error

Unable to read file from location: app/public/img/reportImages/e96b4467-055d-4e5a-8c4e-bf2af6261177.png.

What can I do?

1 like
jj15's avatar

@msslgomez Hmm, that doesn't look like the full/absolute path to the file (from what you showed, it should start out like /home/programador/code/btl-visor-new/storage/app/public...). Can you try using Storage::disk('public')->path("img/reportImages/{$filename}")?

1 like
medcharrafi's avatar

@jj15 did you change anythings in the public key on config/filesystem.php ??

Please or to participate in this conversation.