masterhunter
masterhunter

Reputation: 559

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?

Upvotes: 3

Views: 4509

Answers (3)

Robin Dirksen
Robin Dirksen

Reputation: 3422

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!

Upvotes: 2

suman das
suman das

Reputation: 367

For basic Laravel file system the syntax is :
At very top under namespace write:
use File;

Then in your method use:

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

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

    File::makeDirectory($directoryPath, 0777, true, true);
    //Perform storing
}

Upvotes: 0

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

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);

Upvotes: 0

Related Questions