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]
Realtime Event Broadcasting using Socket.io in Laravel7.x with Example
In the today’s technogy age genuin...Make Authentication System with VueJs and Google Firebase
In this tutorial, we will learn how to i...How to Create and Manage Cron Jobs on Linux
Cron job is time based job schedule whic...How to display all items or values in an array using loop in jQuery
Use the jQuery.each() function The jQ...How to get Local Time Instead of Server Time
Suppose you are managing blog website an...