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.
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);
}
}
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');
}
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.
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]
Laravel Livewire Pagination Example
This post is facile to how to utilize la...Laravel 8 Login with Facebook using Socialite Package
Here, i will show you how to works larav...Laravel 8 Create Dummy Data using laravel/tinker Package
Today we will learn how to engender dumm...How to Install and Use Nano Text Editor in Linux
Many times, working in command line, man...Node.js MySQL Insert rows into Database Table
In this article, we will guide you to ho...