Laravel Create and Delete Directory

  611 views   7 months ago 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.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]