Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking folder already existed and if not create a new folder by id in laravel

i want to store my image to a specific folder and the folder will named by page id. For example if Page id=1, the folder location should be public/pages/page_id/image_here.

If the folder are not existed yet the system will generate and named with their page id.

 $id=1;
 $directoryPath=public_path('pages/' . $id);

if(File::isDirectory($directoryPath)){
        //Perform storing
    } else {
        Storage::makeDirectory($directoryPath);
        //Perform storing
    }

But i having error that "mkdir(): Invalid argument". Can i know why it happen?

And after my research some people say the folder name should based with id+token so intruder cannot search image based on id, is there possible to achieve?

like image 694
masterhunter Avatar asked Jan 01 '26 15:01

masterhunter


2 Answers

I had the same problem, but when I use File instead of Storage it works!

$id=1;
$directoryPath=public_path('pages/'.$id);

//check if the directory exists
if(!File::isDirectory($directoryPath)){
    //make the directory because it doesn't exists
    File::makeDirectory($directoryPath);
}

//Perform store of the file

Hope this works!

like image 116
Robin Dirksen Avatar answered Jan 03 '26 11:01

Robin Dirksen


When you use Storage facade, it uses local disk as default which is configured to work with storage_path().

So, if you want to create directory in public directory, use File::makeDirectory which is just simple wrapper for mkdir() with additional options or use mkdir() directly:

File::makeDirectory($directoryPath);
mkdir($directoryPath);
like image 31
Alexey Mezenin Avatar answered Jan 03 '26 11:01

Alexey Mezenin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!