How to Upload Files to Multiple Folders in Laravel
In this tutorial, we will see how to upload files to multiple folders in Laravel, so let's assume that we want to store an image in two folders one for the users and another one for the backup.
Upload files to multiple folders
So, to upload files to multiple folders add the following code inside your controller.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UploadController extends Controller
{
/**
* Upload files
*/
public function uploadFile(Request $request) {
//save file into multiple folders
$file = $request->file('file');
$this->saveImageForBackup($file);
$this->saveImageForUser($file);
return redirect()->back()->with([
'message' => 'Picture uploaded successfully',
]);
}
/**
* Save image for user
*/
public function saveImageForUser($file)
{
$file_name = time().'_'.'picture'.'_'.$file->getClientOriginalName();
$file->storeAs('user/images/', $file_name, 'public');
}
/**
* Save image for backup
*/
public function saveImageForBackup($file)
{
$file_name = time().'_'.'picture'.'_'.$file->getClientOriginalName();
$file->storeAs('backup/images/', $file_name, 'public');
}
}