I tried uploading multiple files into my database but I keep getting just one file, Am using laravel 5.5 all files show on my file directory path but store only one file into my database. Here is my code
my view
<label for="image">{{ __(' image') }}</label>
<input type="file" name="image[]" class="form-control" value="{{ $employee['image'] }}" multiple>
my route
Route::post('/people/employees/test/{id}', 'EmplController#test');
my controller
if($request->hasfile('image')){
foreach ($request->image as $image) {
$path = $image->getClientOriginalName();
$filename = time() . '-' . $path;
$image->storeAs('employees', $employee->id . '/' . $filename);
$image->move(public_path('employees'),$filename);
i inserted image here->$employee->image = $filename;
$employee->save();
}
}
Make an array, and implode it before insert to table, like :
$files = []; // an empty array
foreach($a as $b) {
$files[] = $b->name; // insert name to array
}
$files = implode(",", $files); // insert $files into your table
So you need to change on your code :
if($request->hasfile('image')){
$files = []; // make an array
foreach ($request->image as $image) {
$path = $image->getClientOriginalName();
$filename = time() . '-' . $path;
$files[] = $filename; // insert to array
$image->storeAs('employees', $employee->id . '/' . $filename);
$image->move(public_path('employees'), $filename);
}
$files = implode(",", $files); // insert $files into your table
}
Related
I created a user table with employee's details, and in my image column I have a file uploaded in its cell. How can I keep old file every time I upload a new file.
my view.blade
<input type="file" name="image[]" class="form-control" value="{{ $employee['image'] }}" multiple>
<th> {{$employee['image']}}</th>
my controller
if($request->hasfile('image')){
$files = [];
foreach ($request->image as $image) {
$path = $image->getClientOriginalName();
$filename = time() . '-' . $path;
$files[] = $filename;
$image->storeAs('employees', $employee->id . '/' . $filename);
$image->move(public_path('employees'),$filename);
}
$files = implode("</br>;", $files);
}
$employee->image = $files;
$employee->save();
Just change one line :
$employee->image = $files;
to,
$employee->image = $employee->image . $files;
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';
}
May be you are looking for this kind of stuff:-
if ($request->hasFile('files')) {
$files = $request->file('files');
foreach($files as $file){
$extension = $file->getClientOriginalExtension();
$fileName = str_random(5)."-".date('his')."-".str_random(3).".".$extension;
$folderpath = 'images'.'/';
$file->move($folderpath , $fileName);
}
}
<input type="file" id="gallery" name="files[]" multiple />
I am thinking u may missed this part
<input type="file" id="gallery" name="file[]" />
note the file[] it must be array otherwise it will only save the last image if upload multiple image
If u did ur html part correct, then use like this,
foreach ($file as $photo) {
$path = Storage::putFile('foldername', $photo);
}
try this code:
$files= Input::file('image');
$destinationPath= 'images';
$images=array();
foreach($files as $file){
$fullname= $file->getClientOriginalName();
$hashname = $fullname;
$upload_success =$file->move($destinationPath, $hashname);
$images[]=$fullname;
$has= implode(",",$images);
}
$modelname= new Modelname;
$modelname->image_attachment = $has;
$modelname->save();
and yout html page:
<input type="file" id="image" name="image[]" />
It is not that complicated.
As of larval 5.8 you can do this:
collect($request->images)->each(function ($image) {
return $image->store('images', 'public');
});
It puts images in images folder of public disk.
I have upload form where I'm able to upload any type of files and save their path to database. Without saving any relevant information in database such as: filetype, filesize etc can I get this information while I loop the results and showing them on page?
Here is what I tried so far
public function fileUpload()
{
$allFiles = Documents::paginate(20);
$files = array();
foreach ($allFiles as $file) {
$files[] = $this->fileInfo(pathinfo(public_path() . '/uploads/' . $file));
}
return View::make('admin.files', [
'files' => $files
]);
}
public function fileInfo($filePath)
{
$file = array();
$file['name'] = $filePath['filename'];
$file['extension'] = $filePath['extension'];
$file['size'] = filesize($filePath['dirname'] . '/' . $filePath['basename']);
return $file;
}
The error which I get when I run the page is
ErrorException: filesize(): stat failed for .....
Is this the correct way of doing this?
Update: dd($filePath['dirname'] . '/' . $filePath['basename']); return
string(126) "/var/www/html/site/public/uploads/{"id":2,"document_path":"aut6MnADFrPZTz4TJf0Y.pdf","document_name":"Some title for the file"}"
Change this line
$files[] = $this->fileInfo(pathinfo(public_path() . '/uploads/' . $file));
to
$files[] = $this->fileInfo(pathinfo(public_path() . '/uploads/' . $file->document_path));
Here is my controller code:
$images = Input::file('images');
foreach($images as $image){
$filenames = date('Y-m-d-H-i-s') . '-' . $image->getClientOriginalName();
$imageFolder = 'clients';
$image->move($imageFolder , $filenames);
echo $filenames;
}
I was trying to upload multiple image files and could do that. Now I want to save all the file names as an array or as whatever is the best in the database.
I tried to use serialize() laravel 4.2 says serialization is not allowed for uploading.
Any idea ? Thanks.
Try this ::
$images = Input::file('images');
$filenames = array();
foreach($images as $image){
$filenames [] = date('Y-m-d-H-i-s') . '-' . $image->getClientOriginalName();
$imageFolder = 'clients';
$image->move($imageFolder , $filenames);
echo $filenames;
}
I am slowly working on a image uploader, and wondering why when echoing my renamed files, its giving me a single character instead of the whole thing.
Any reason it would be doing that?
It does tho, successfully upload the image as a phil_546d196082606.jpg with a different number for each image
Here is my code
<?php
if (isset($_POST['addpart'])) {
$image = $_FILES['images']['tmp_name'];
$name = $_POST['username'];
$i = 0;
foreach ($image as $key) {
$fileData = pathinfo(basename($_FILES["images"]["name"][$i]));
$fileName = $name .'_'. uniqid() . '.' . $fileData['extension'];
move_uploaded_file($key, "image/" . $fileName);
copy("image/" . $fileName, "image_thumbnail/" . $fileName);
$i++;
}
echo 'Uploaded<br>';
$fileName1 = $fileName[0];
$fileName2 = $fileName[1];
$fileName3 = $fileName[2];
echo 'Main Image - '.$fileName1.'<br>';
echo 'Extra Image 1 - '.$fileName2.'<br>';
echo 'Extra Image 2 - '.$fileName3.'<br>';
echo '<hr>';
}
?>
$filename is a string and strings in php are arrays where each letter has an index $filename[o] is the first letter and so on.Use
$filename[]=$name .'_'. uniqid() . '.' . $fileData['extension'];
Try the below block of code
$fileName[] = $name .'_'. uniqid() . '.' . $fileData['extension'];
move_uploaded_file($key, "image/" . end($fileName));
copy("image/" . end($fileName), "image_thumbnail/" . end($fileName));
$fileName = $name .'_'. uniqid() . '.' . $fileData['extension'];
Filename is the string. It is : $name . number.
Like philip12345.
So if we have:
philip
012345
$fileName[0] = p
$fileName[1] = h
Also you overwrite filename in each loop. Try to save it to an array and print it, here is some code:
$fileNames = array();
foreach ($image as $key)
{
$fileName = $name .'_'. uniqid() . '.' . $fileData['extension'];
fileNames[$i] = $fileName;
}
echo $fileNames[0];
echo $fileNames[1];
echo $fileNames[2];
You could also use a foreach loop to go over the array with the filenames and print each element, this is cool because it will works with any number of images, not just 3:
foreach ($fileNames AS $key2)
{
echo ($key2);
}