PhoenixRebirthed
PhoenixRebirthed

Reputation: 462

How do I create a subfolder in the Laravel Store

I'd like to create a subfolder in storage like /storage/app/public/user_folder

Does anyone know how to do it with the proper permissions?

Upvotes: 0

Views: 3309

Answers (2)

nxu
nxu

Reputation: 2272

The easiest way is to simply use mkdir. Assuming 775 is the proper permission for you:

mkdir(storage_path('app/public/user_folder'), 0775)

Upvotes: 1

Mark
Mark

Reputation: 1376

Your question is a bit vague, but I'm going to assume you want to do it programmatically, perhaps from within a controller?

So lets make use of Laravel's Filesystem class to help us do this.

At the top of your controller, lets bring it in like so: use Illuminate\Filesystem\Filesystem;

Now we can instantiate it. $file = new Filesystem();. And I might do it like this:

    $file = new Filesystem();
    $username = 'userNameGoesHere';
    $directory = 'directory/goes/here/' . $username;
    if ( $file->isDirectory(storage_path($directory)) )
    {
        return 'Directory already exists';
    }
    else
    {
        $file->makeDirectory(storage_path($directory), 755, true, true);
        return 'Directory has been created!';
    }

Now, lets break down what we just did. First, we check if the directory exists. It's just good practice to do this, I think. If not, then we create it.

Lets break down what the arguments for makeDirectory() are. First is the system file path. We make use of the storage_path() helper that Laravel gives us to point us to the storage directory. Then we pass in the directory. The second argument is the chmod permissions for that directory. By default it is set to 493. Third, we set the directory creation to be recursive, meaning it will create each directory in your path. Default for recursive is false. The final argument tells the directory creation to force it. If you didn't check if the directory exists and attempted to create it anyway without setting this to true, Laravel would throw an exception complaining that the directory already exists. If it's set to true Laravel just recreates the directory anyway.

You can read more about the Filesystem class here.

I hope this helps.

Upvotes: 2

Related Questions