how to update multiple images in laravel? - php

i want store the images for product the product having multiple images the problem is that i want to update the images problem is images are updated but the entry never goes to database. instead it stores same entry two times.
if($request->hasfile('image')) { //here i got images
$file = $request->file('image');
$file_count= count($file); //for updating multiple images
for ($i=0; $i < $file_count; $i++) {
$imagesize = $file[$i]->getClientSize();
$imageexten = $file[$i]->getClientOriginalExtension();
$product_image_count = count($request->productimagename);
for ($i=0; $i < $product_image_count; $i++) {
if($file_count != 1) {
$new_name = $request->productimagename[$i].$i.".".$imageexten;
} else {
$new_name = $request->productimagename[$i].".".$imageexten;
}
$product_image_path ='images/frontendimage/product_image/'.$new_name;
Image::make($file[$i])->save($product_image_path);
foreach ($product->images as $key => $value) {
product_image::find($value->id)->where('product_id','=',$product->id)
->update(['image_name'=> $new_name,'image_url'=>$product_image_path,
'modified_by'=>Auth::user()->id]);
}
}
}
}

if ($request->has('unit_images'))
{
$promotion = [];
foreach ($request->file('unit_images') as $key => $file) {
$filenameWithExt = $file->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $file->getClientOriginalExtension();
$fileNameToStore = uniqid() . '.' . $extension;
$path = $file->storeAs("$directory/unit_images/$b/$unit_num", $fileNameToStore, 'public');
$this->validate($request, [
'images' => 'dimensions:min_width=250,min_height=250'
]);
$b_id = $request->building_name;
$unitimg = UnitImage::where('unit_id', '=', $unit_store_id)->get();
$new=strlen($unitimg);
if ($new!='2') {
foreach ($unitimg as $get2) {
$get2->delete();
}
$nn=New UnitImage();
$nn->images = $path;
$nn->unit_id = $unit_store_id;
$nn->save();
}
if ($new=='2') {
$nn = New UnitImage();
$nn->images = $path;
$nn->unit_id = $unit_store_id;
$nn->save();
}
}
}

Input Field -
<input type="file" name="images[]" class="form-control" multiple required />
Controller -
$imagesName = array();
$imagesPath = array();
if($files=$request->file('images')){
foreach (Input::file('images') as $file) {
$name = strtolower($file->getClientOriginalName());
$name = preg_replace('/\s+/', '_', $name);
$img = Image::make($file);
$path = 'your/path/'.$name;
$img->save($path);
$imagesName[] = $name;
$imagesPath[] = $path;
}
}
This will upload multiple images to your server and you will get uploaded image names from $imagesName[] and path from $imagesPath[].
Now you can use those according to your BD structure.

Related

PHP/MySQL - Data entered twice when doing single upload

I am trying to upload image to database MySQL. But I have a problem, when I am trying to upload one image, the image inserted twice.
For example:
I have "A.jpg" if I try to upload it
the inserted data will be like "A.jpg,A.jpg"
What I want in database "A.jpg"
and if I try to upload multiple images like "A.jpg,B.jpg and C.jpg"
the inserted data will be like "B.jpg,B.jpg,C.jpg,C.jpg"
What I want in database "A.jpg,B.jpg,C.jpg"
I've tried to search on google but no results, anyone can help me to resolve this problem ? Thanks
Here is my code :
include('koneksi.php');
date_default_timezone_set('Asia/Jakarta');
$id_user = $_POST['id_user'];
$caption = $_POST['caption'];
$files = [];
foreach($_FILES['files']['name'] as $i => $name) {
$name = $_FILES['files']['name'][$i];
$size = $_FILES['files']['size'][$i];
$type = $_FILES['files']['type'][$i];
$tmp = $_FILES['files']['tmp_name'][$i];
$explode = explode('.', $name);
$ext = end($explode);
$updatdName = $explode[0] . time() .'.'. $ext;
$path = 'gallery/';
$path = $path . basename( $updatdName );
if(empty($_FILES['files']['tmp_name'][$i])) {
$errors[] = 'Please choose at least 1 file to be uploaded.';
}else {
$allowed = array('jpg','JPG','jpeg','JPEG','gif','GIF','bmp','BMP','png','PNG');
$max_file_size = 1024*1024*2;; // 2MB
if(in_array($ext, $allowed) === false) {
$errors[] = 'The file <b>'.$name.'</b> extension is not allowed.';
}
if($size > $max_file_size) {
$errors[] = 'The file <b>'.$name.'</b> size is too hight.';
}
}
if(empty($errors)) {
// if there is no error then set values
$files['file_name'][] = $updatdName;
$files['size'][] = $size;
$files['type'][] = $type;
$errors = array();
if(!file_exists('gallery')) {
mkdir('gallery', 0777);
}
if(move_uploaded_file($tmp, $path)) {
echo '<script>window.history.back()</script>';
}else {
echo 'Something went wrong while uploading
<b>'.$name.'</b>';
}
}else {
foreach($errors as $error) {
echo '<p>'.$error.'<p>';
}
}
}
if(!empty($files)) {
$files['file_name'][] = $updatdName;
$files['size'][] = $size;
$files['type'][] = $type;
$names = implode(',', $files['file_name']);
$sizes = implode(',', $files['size']);
$types = implode(',', $files['type']);
$sql="INSERT into status VALUES(NULL, '$id_user', '$names','$caption','foto',NOW()); ";
mysqli_query($koneksi, $sql);
}
You're setting $files['file_name'][] in the while loop and also right before inserting into the DB. You just need to remove 2nd call to $files['file_name'][] = $updatdName;
Here is a simplified version of what you're doing.
<?php
$_FILES[] = ['name' => 'A'];
$_FILES[] = ['name' => 'B'];
$_FILES[] = ['name' => 'C'];
$files = [];
foreach ($_FILES as $file) {
$updatdName = $file['name'];
// You're setting it here
$files['file_name'][] = $updatdName;
}
if (!empty($files)) {
// And also here.
$files['file_name'][] = $updatdName;
$names = implode(',', $files['file_name']);
echo $names;
}

Laravel : How to save multiple image file to database

I want to save multiple image files with different field in database such as product_image, feature_image, slurp_image. I used following controller method to save the image files
public function store(Request $request)
{
$product = new Product();
if($request->hasFile('product_image'))
{
$file = Input::file('product_image');
$imageName = time().'.'.$request->product_image->getClientOriginalExtension();
$product->product_image = $imageName;
$file->move('images/', $imageName);
}
if($request->hasFile('feature_image'))
{
$file = Input::file('feature_image');
$imageName = time().'.'.$request->feature_image->getClientOriginalExtension();
$product->feature_image = $imageName;
$file->move('images/', $imageName);
}
if($request->hasFile('slurp_image'))
{
$file = Input::file('slurp_image');
$imageName = time().'.'.$request->slurp_image->getClientOriginalExtension();
$product->slurp_image = $imageName;
$file->move('images/', $imageName);
}
// dd($product->product_image);
// dd($product->feature_image);
// dd($product->slurp_image);
$product->save();
}
when i dd() the $product->product_image,$product->feature_image, $product->slurp_image i saw different different file name , but after it stored into the database i saw same file stored into database in different different field.
anyone help to find out what could be the solution please?
When you're uploading multiple images at once you'd be passing through an array of images.
This is what my controller function has looked like when I've done this previously.
public function multiple_upload() {
// get the files
$files = Input::file('images');
// counting of uploaded images
$file_count = count($files);
// start count how many uploaded
$uploadcount = 0;
foreach ($files as $file) {
$rules = array('file' => 'required'); //'required|mimes:png,gif,jpeg,txt,pdf,doc'
$validator = Validator::make(array('file'=> $file), $rules);
if($validator->passes()){
$destinationPath = 'uploads'; // upload folder in public directory
$filename = $file->getClientOriginalName();
$upload_success = $file->move($destinationPath, $filename);
$uploadcount ++;
// save into database
$extension = $file->getClientOriginalExtension();
$entry = new Uploads();
$entry->mime = $file->getClientMimeType();
$entry->original_filename = $filename;
$entry->filename = $file->getFilename().'.'.$extension;
$entry->save();
}
}
if($uploadcount == $file_count){
Session::flash('success', 'Upload successfully');
return Redirect::to('upload');
} else {
return Redirect::to('upload')->withInput()->withErrors($validator);
}
}
In your example, I'd image it would be more like this
$product = new Product();
//upload multiple files
$files= [];
if($request->file('leftimage')) $files[] = $request->file('leftimage');
if($request->file('Middleimage')) $files[] = $request->file('Middleimage');
if($request->file('Rightimage')) $files[] = $request->file('Rightimage');
foreach($files as $file)
{
if(!empty($file))
{
$filename[] = $file->getClientOrginalName();
if(isset($filename)){
$file->move(base_path().'/frontend/sidimage/',end($filename));
}
}
$product->image1 = $filename[0];
$product->image2 = $filename[1];
$product->image3 = $filename[2];

Upload multiple files and return file info as object [duplicate]

This question already has answers here:
Multiple returns from a function
(32 answers)
Closed 6 years ago.
I am trying to create a simple uploader class to use uploading multiple images. I need to return file info from uploadFiles method and use it inside another method (uploadGalleryImages). However if I use return $result then foreach loop stops after first file is uploaded. If I don't return it and just use print_r($result) I can upload all files and see the object in chrome's network tab. Here is my simplified code:
public function uploadGalleryImages() {
$upload_image = $this->uploadFiles($_FILES['image']);
}
private function reArrayFiles($files) {
$array = array();
$file_count = count($files['name']);
$file_keys = array_keys($files);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$array[$i][$key] = $files[$key][$i];
}
}
return $array;
}
private function uploadFiles($files = array()) {
$upload_dir = IMAGE_UPLOAD_DIR;
$thumb_dir = $upload_dir . 'thumbnails/';
$file_array = $this->reArrayFiles($files);
foreach ($file_array as $file) {
$base_name = pathinfo($file['name'], PATHINFO_FILENAME);
$extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
$counter = 1;
while(file_exists($upload_dir . $file['name'])) {
$file['name'] = $base_name . $counter . '.' . $extension;
$counter++;
};
if (move_uploaded_file($file['tmp_name'], $upload_dir . $file['name'])) {
$result = new \stdClass();
$result->file_name = $file['name'];
$result->extension = $extension;
//print_r($result);
return $result; // Stops after first file uploaded
} else {
return false;
}
}
}
Store all picture objects in array and return it. Simple example:
$pics = [];
foreach ($file_array as $file) {
if (move_uploaded_file($file['tmp_name'], $upload_dir . $file['name'])) {
$result = new \stdClass();
$result->file_name = $file['name'];
$result->extension = $extension;
$pics[] = $result;
}
}
return $pics;

Multiple Image Upload in Laravel 5.2

Finally I can upload and move the images, but now I want to create a multiple upload images on Laravel. Is that possible? Did I have to use array to make it?
Can I just modify a little bit from this code?
It's on my ProductController.php
$picture = '';
if ($request->hasFile('images')) {
$file = $request->file('images');
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$picture = date('His').$filename;
$destinationPath = base_path() . '\public\images/';
$request->file('images')->move($destinationPath, $picture);
}
if (!empty($product['images'])) {
$product['images'] = $picture;
} else {
unset($product['images']);
}
Thank you.
Note: My code above is from a kindhearted person on stackoverflow, thanks again ;)
At your frontend form you'll have to use your field attribute name like
name="images[]"
And your controller code would be like this.
$picture = '';
if ($request->hasFile('images')) {
$files = $request->file('images');
foreach($files as $file){
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$picture = date('His').$filename;
$destinationPath = base_path() . '\public\images';
$file->move($destinationPath, $picture);
}
}
if (!empty($product['images'])) {
$product['images'] = $picture;
} else {
unset($product['images']);
}
Your input from $_POST will be coming in as an array. All you need to do is to iterate through it:
$picture = '';
if ($request->hasFile('images')) {
$files = $request->file('images');
foreach($files as $file){
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$picture = date('His').$filename;
$destinationPath = base_path() . '\public\images/';
$request->file('images')->move($destinationPath, $picture);
}
}
Slight modified code to upload multiple image.
public function store(Request $request)
{
$pid = $request->input('pid');
$input = $request->file('images');
$picture = array();
if($request->hasFile('images')) :
foreach ($input as $item):
$extension = $item->getClientOriginalName();
$name = date('Ymd') . '.' . $extension;
$destinationPath = base_path() . '/uploads/images/';
$item->move($destinationPath, $name);
$arr[] = $name;
endforeach;
$picture = implode(",", $arr);
else:
$picture = '';
endif;
DB::table('document')->insert(array('pid' => $pid,'image' => $picture));
Session::flash('message', 'Multiple pictures are uploaded successfully');
return redirect('/image-upload');
}

PHP/HTML form upload multiple images

I have this in my form:
<input type="file" name="images[]" multiple="multiple" />
then this PHP on the action page for the form:
$files = array();
$fdata = $_FILES["images"];
if(is_array($fdata["name"]))
{
//This is the problem
for ($i = 0; $i < count($fdata['name']); ++$i)
{
$files[] = array(
'name' => $fdata['name'][$i],
'tmp_name' => $fdata['tmp_name'][$i],
);
}
}
else
{
$files[] = $fdata;
}
foreach ($files as $file)
{
move_uploaded_file ( "$pic1_name","$image1") or die("image 1 did not copy<br>");
}
but i know i have the move_uploaded_file line wrong. what do i need to put in here instead?
UPDATE:
my latest code is as follows:
$files = array();
$fdata = $_FILES["images"];
if(is_array($fdata["name"]))
{
//This is the problem
for ($i = 0; $i < count($fdata['name']); ++$i)
{
$files[] = array(
'name' => $fdata['name'][$i],
'tmp_name' => $fdata['tmp_name'][$i],
);
}
}
else
{
$files[] = $fdata;
}
foreach($_FILES['images'] as $file)
{
echo $file['tmp_name'];
move_uploaded_file($file['tmp_name'], $_SERVER["DOCUMENT_ROOT"].'/img/project-gallery/test');
}
I would try something like this...of course add in some validation to make sure users are uploading only file-types which you expect
$currentDate = microtime();
$storeFolder = $_SERVER["DOCUMENT_ROOT"] . "/yourSavePath/";
$fileNames = array();
foreach ($_FILES['images']['name'] as $key => $value) {
if (!empty($_FILES['images'])) {
//tempfile is the file which has actually been stored on your server
$tempFile = $_FILES['images']['tmp_name'][$key];
//prepend the time so to make filenames unique...the filename here is the one the user sees and the temp filename above is one generated by the server
$targetFile1 = $currentDate . $_FILES['images']['name'][$key];
//get rid of spaces in the name since they can cause issues
$targetFile1 = str_replace(' ', '_', $targetFile1);
$res = move_uploaded_file($tempFile, $storeFolder . $targetFile1);
$fileNames[] = $targetFile1;
}
}

Categories