Reputation: 119
I've been playing with multiple files and I've successfully managed how to upload multiple files (in my case images) into the public/storage folder in Laravel, but I want to upgrade the method to dynamically create a folder based on user ID.
In a nutshell, when user select let's say 10 images, hit the submit button, a folder with his ID will be created and then those 10 images will end up in this folder.
This is my function to store the images:
public function store(Request $request) {
$files = $request->file('file');
if(!empty($files)):
foreach($files as $file):
Storage::disk('photos')->put($file->getClientOriginalName(), file_get_contents($file));
endforeach;
endif;
}
And the filesystem:
'photos' => [
'driver' => 'local',
'root' => public_path('../public/storage'),
],
Now I am stuck here and can't get it how to make it working. Would appreciate any help.
Upvotes: 0
Views: 7753
Reputation: 10714
Just create the folder if it doesn't exist :
public function store(Request $request) {
$files = $request->file('file');
$folder = public_path('../public/storage/' . Auth::id(); . '/');
if (!Storage::exists($folder)) {
Storage::makeDirectory($folder, 0775, true, true);
}
if (!empty($files)) {
foreach($files as $file) {
Storage::disk(['drivers' => 'local', 'root' => $folder])->put($file->getClientOriginalName(), file_get_contents($file));
}
}
}
Upvotes: 2
Reputation: 662
This is how i did it with Image Intervention Library, using File instead of Storage didn't gave me an error. I am using Laravel 5.6
Note:I am getting post id from view to controller for my scenario,then saving the post under the directory after creating a folder for the user based on user id if exists.I am also using storage_path instead of public path,you can change it according to your need
use File;
use Image; //Image Intervention library
public function storeImages(Request $request,$id)
{
$post = Post::find($id); //getting the post id from blade
$image = $request->file('image');
$folder = storage_path('/app/posts/' . Auth::id() . '/' . $post->id . '/');
$filename = time() . '.' . $image->getClientOriginalExtension();
if (!File::exists($folder)) {
File::makeDirectory($folder, 0775, true, true);
$location = storage_path('/app/posts/' . Auth::id() . '/' . $post->id . '/' . $filename);
Image::make($image)->resize(800,400)->save($location); //resizing and saving the image
}
}
Upvotes: 1