In this tutorial, you will learn how to create directory in laravel storage if it doesn’t exists. We will be also discussing how you can select the storage and how you can create nested directories in laravel.
Lets get started.
Table of Contents
Syntax for Creating Directory:
To create a directory in laravel, we will be using makeDirectory
function of Storage
:
Storage::makeDirectory('folder_name');
This will create the directory if it doesn’t exist and if it exists, it will do nothing.
1: For creating single directory:
Let’s assume we have to create my
directory in the storage. We will add the following code:
Storage::makeDirectory('my');
This will create the my
directory in the storage.
2: For creating nested directories:
Lets assume we need to create nested directories, my/thumbnails/photos
, we will add the following code:
Storage::makeDirectory('my/thumbnails/photos');
How to specify the Storage Disk when Creating Directory?
To specify the storage disk, we will be using disk()
method with makeDirectory
:
Storage::disk('public')->makeDirectory('my/thumbnails/photos');
This will create the nested directories my/thumbnails/photos
in storage public
folder.
You can also use S3
at the place of public
, in order to save files in S3
.
How to Create Directory in the route?
To create the directory in the routes itself, go to the routes/web.php
and add the following code:
Route:get('createdirectory', function () {
Storage::disk('public')->makeDirectory('my/thumbnails/photos');
});
Conclusion
Hope in the above article, you have learned how to create single or nested directories in laravel storage if it doesn’t exist. See you in the next one 🙂
Write a Reply or Comment