How to upload folder in laravel?

by darrion.kuhn , in category: PHP Frameworks , 3 months ago

How to upload folder in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by hal.littel , 3 months ago

@darrion.kuhn 

To upload a folder in Laravel, you can use the Storage facade which provides a simple way to work with files and folders in Laravel. Here is a step-by-step guide on how to upload a folder in Laravel:

  1. Create a form in your view file which allows users to select a folder to upload:
1
2
3
4
5
<form action="{{ route('uploadFolder') }}" method="POST" enctype="multipart/form-data">
    @csrf
    <input type="file" name="folder" directory webkitdirectory />
    <button type="submit">Upload Folder</button>
</form>


  1. Create a route to handle the form submission and process the upload in your routes/web.php file:
1
Route::post('/upload-folder', 'FolderController@uploadFolder')->name('uploadFolder');


  1. Create a controller to handle the folder upload process using the store method in your FolderController.php file:
1
2
3
4
5
6
7
8
use IlluminateSupportFacadesStorage;

public function uploadFolder(Request $request)
{
    $folderPath = $request->file('folder')->store('uploaded_folders');

    return redirect()->back()->with('success', 'Folder uploaded successfully.');
}


  1. Make sure to add the appropriate disk configuration in your config/filesystems.php file:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
'disks' => [
    'local' => [
        'driver' => 'local',
        'root' => storage_path('app'),
    ],
    'public' => [
        'driver' => 'local',
        'root' => storage_path('app/public'),
        'url' => env('APP_URL').'/storage',
        'visibility' => 'public',
    ],
]


  1. Make sure to create a storage link by running the following command in your terminal:
1
php artisan storage:link


Now, users should be able to upload a folder by selecting it in the form, and the folder will be stored in the specified directory on the server.