How to Create folders recursively in Laravel (with Example)

In this simple example I will show you how to create recursive directories in Laravel. Sometimes you need to create directories recursively in your Laravel application.

How to Create folders recursively in Laravel (with Example)

In custom php you may have to check within if-else condition for existing or non existing directories and then create ones which do not exist.

But I will show with help of an example to create recursive directories in Laravel with single line of code.

Assume that you are storing profile images within a folder named by the id of the user. So the full path would be something like:

storage_path() . "profile/{user_id}/avatar". In place of user_id there will be actual ID of the user such as 1,2,3..etc.

To create the avatar directory recursively you need to write the following code:

if (!\File::exists( storage_path("profile/" . $user->id . "/avatar") )) {
    \File::makeDirectory($invoice_path, 0755, true);
}

It will create recursive directories in path including the “avatar” directory. So the final path would be your_app/storage/profile/1/avatar

I hope it helps you!

Leave a Reply