I have this function in my controller:
use File;
use Image; //image intervention library
...
public function upload(Request $request)
{
//make sure there is a folder in public with the username
$username = Auth::user()->name;
$folderpath = public_path('images/' . $username . '/');
File::makeDirectory($folderpath, $mode = 0777, true, true);
$files = $request->file;
if(!empty($files)):
foreach($files as $file):
$filename = 'post_' . time() . '.' . $file->getClientOriginalExtension();
$path = $folderpath . $filename;
Image::make($file)->resize(800,400)->save($path);
endforeach;
endif;
return 'success';
}
which only save the last image if I upload multiple.
and I tried:
public function upload(Request $request)
{
//make sure there is a folder in public with the username
$username = Auth::user()->name;
$folderpath = public_path('images/' . $username . '/');
File::makeDirectory($folderpath, $mode = 0777, true, true);
$files = $request->file;
if(!empty($files)):
foreach($files as $file):
$filename = 'post_' . time() . '.' . $file->getClientOriginalExtension();
$path = $folderpath . $filename;
$file->save($path);
endforeach;
endif;
return ''success;
}
which throw me error:
Method save does not exist.
I goggled and it seems like I did not instantiate it with model. But in this case, how can I instantiate it with model if it is just a direct file upload?
What is the best way for multiple images upload in laravel
?
Update
After reading @kunal's answer, I managed to solve the issue by adding a unique number for the file name:
public function upload(Request $request)
{
//make sure there is a folder in public with the username
$username = Auth::user()->name;
$folderpath = public_path('images/' . $username . '/');
File::makeDirectory($folderpath, $mode = 0777, true, true);
$files = $request->file;
$count = 0;//<-- add a counter
if(!empty($files)):
foreach($files as $file):
$filename = 'post_' . time() . '_' . $count . '.' . $file->getClientOriginalExtension();//<-- add counter to the file name
$path = $folderpath . $filename;
Image::make($file)->resize(800,400)->save($path);
$count ++;//<-- increase the value
endforeach;
endif;
return 'success';
}