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

Question

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

Answers 3
Added at 2017-01-02 10:01
Tags
Question

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?

Answers to

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

nr: #1 dodano: 2017-01-02 10:01

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

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

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

Hope this works!

nr: #2 dodano: 2017-01-02 10:01

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);
nr: #3 dodano: 2017-01-02 11:01
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
}
Source Show
◀ Wstecz