How to create and delete directory in Laravel

Managing files in web application is one of important stuff. You probably don't want to put all files in single directory. Instead it is better to create dynamic directory structure and put files according to username or file type. This also makes you easy to find the file in directory.

In this article, we will see examples how you can create, rename and delete directory in Laravel.

Create directory

You can create directory using static makeDirectory() method from File class.

/**
 * store data
 * 
 * @param \Illuminate\Http\Request $request
 *
 * @return \Illuminate\Auth\Access\Response
 */
public function store(Request $request)
{
    $is_created = \File::makeDirectory('images/avatar/', $mode = 0777, true);

    echo($is_created); // 1
}

Of course, you may only want to create the directory, if it is not exist. So it is better to check if th directory exists or not.

/**
 * store data
 * 
 * @param \Illuminate\Http\Request $request
 *
 * @return \Illuminate\Auth\Access\Response
 */
public function store(Request $request)
{
    $path = 'images/avatar/';
    
    if (\File::exists($path)) {
        echo('Directory already exists.');
    } else {
        \File::makeDirectory($path, $mode = 0777, true);
    }
}

Copy directory

Same way you can copy the current directory to new.

/**
 * update data
 * 
 * @param \Illuminate\Http\Request $request
 *
 * @return \Illuminate\Auth\Access\Response
 */
public function update(Request $request)
{
    \File::copyDirectory('images/avatar/', 'images/profile');
}

Delete directory

If you want to delete directory, you can use delete() method from File class. Obviously before deleting folder, we need to check if folder exists or not to prevent error occurance.

/**
 * destroy data
 * 
 * @param \Illuminate\Http\Request $request
 *
 * @return \Illuminate\Auth\Access\Response
 */
public function destroy(Request $request)
{
    $path = 'images/avatar/1/';

    if(File::exists($path)) {
        File::delete($path);
    }
}

This way you can manage directory in Laravel. Please let us know in the below comment section.

Tags: