DEV Community

Ayowande Oluwatosin
Ayowande Oluwatosin

Posted on

Create a folder if not exist

We create a directory is not exist using the File::makeDirectory() function.

The function takes four arguments:

  • $path: This is a string that represent the path of the directory/folder we want to create.
  • $mode: This is used to set the permission for the directory. it is a four- digit integer.
  • $recursive: This is used to specify if the recursive mode is set. it is a Boolean value.
  • $force: this is optional. when set, you may create a file in the path even if the directories in the path does not exist. it takes a Boolean value.

For example, assume we want to create a folder called 'tutorial' in the public path in Laravel. Note: the public path is also the public folder.

$path = public_path('tutorial');
//check if folder exist in path
if (!File::isDirectory($path)) {
    File::makeDirectory($path, $mode = 0777, true, true);
} else {
    logger('folder exist already');
}
Enter fullscreen mode Exit fullscreen mode

Note: there are different path function Laravel provides.

  • base_path(): create the folder in the application root directory
  • public_path(): create the folder in the public directory (public/).
  • storage_path(): create the folder in the storage directory (storage/).
  • app_path(): create the folder in the app directory (app/).

Top comments (0)