Multiple images upload not working Laravel - php

I'm trying to store multiple images to the database but it only stores one image. I don't see any errors. I have tried this but it stores images in public folder, I want the images to be stored in database. How can I fix this? any help would be appreciated.
Controller
if($request->hasFile('files')){
$files = $request->file('files');
foreach ($files as $file) {
$filename = $file->getClientOriginalName();
$images = $file->store('public/photos');
}
}
ProductsPhoto::create([
'product_id' => $product->id,
'filename' => $images
]);
Blade
<input type="file" name="files[]">

I see one issue on your code, you are moving images correctly but storing it in DB outside of loop, which will only store last iteration of loop in DB, you can use this code to store multiple images in DB
if($request->hasFile('files')){
$store_file = [];
$files = $request->file('files');
foreach ($files as $file) {
$filename = $file->getClientOriginalName();
$images = $file->store('public/photos');
$store_file[] = [
'product_id' => $product->id,
'filename' => $images
];
}
ProductsPhoto::insert($store_file);
}

Related

How to save images with different names?

I'm dealing with a few issues regarding multiple images uploads. My project deals with a form the user inputs multiple images that save to a database, but first temporarily stores the images in a directory to show a preview of sorts. In my class, which deals with the uploading of the image I am trying to rename the images as seen below.
I uploaded seven images on the dropdown.
I see that all its images were stored in the database by one.
While it had to be stored under different names.
Controller
public function store(Product $product, Request $request)
{
$path = null;
if ($request->hasFile('file'))
{
$file = $request->file('file');
$name = time();
$extension = $file->getClientOriginalExtension();
$fileName = $name . '.' . $extension;
$path = $file->storeAs($this->path, $fileName, 'public');
}
$gallery = Gallery::create([
'product_id' => $product->id,
'image' => $path,
]);
return response()->json($gallery);
}
$file = $request->file('file');
$name = date('YmdHi');
$extension = $name.$file->getClientOriginalExtension();
In controller , just replace it.

Laravel Upload Multiple Images all records with same name and not moved files

I am new in Laravel and I develop a web application where someone can upload a car ad and other users can write comments bellow that. Instead of developing a simple CRUD application I thought about developing also a table that will be related to these ads and will store the photos. Up to this point, I have made the relations, I can show images and I have two problems: The first problem is that not all images are moved to storage/photos folder and the second problem is that all the records in the database have the same name. For example, if I want to upload images 1,2,3 then in the database all the files will have the name 1.
Bellow, you may find the store code. This code stores all the ads and also the images if they exist.
public function store(Request $request)
{
//
$this->validate($request, [
'name' => 'required',
'cc' => 'required',
'desc' => 'required',
'date' => 'required'
]);
$ad = new Ad;
$ad->name = $request->input('name');
$ad->cc = $request->input('cc');
$ad->desc = $request->input('desc');
$ad->date = $request->input('date');
$ad->user_id = auth()->user()->id;
$ad->save();
if ($request->hasFile('photos')) {
$allowedfileExtension = ['pdf', 'jpg', 'png', 'docx'];
$files = $request->file('photos');
foreach ($files as $file) {
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
//$file->move('storage/photos', $filename);
$check = in_array($extension, $allowedfileExtension);
if ($check) {
foreach ($request->photos as $photo) {
$photo->move('storage/photos', $filename);
$img = new AdsPhoto;
$img->ad_id = $ad->id;
$img->filename = $filename;
$img->save();
}
return redirect('/home')->with('success', 'ad + image created');
} else {
echo '<div class="alert alert-warning"><strong>Warning!</strong> Sorry Only Upload png , jpg , doc</div>';
}
}
}
return redirect('/home')->with('success','ad created');
}
Thank you in advance!
1st mistake, you did looping twice
2nd mistake (you might not realize this) you didnt merge the filename and extension, this will cause an issue when you retrieving the image in blade
therefore correction on your code plus comment to explain it
if ($request->hasFile('photos')) {
$allowedfileExtension = ['pdf', 'jpg', 'png', 'docx'];
$files = $request->file('photos');
foreach ($files as $file) {
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
//$file->move('storage/photos', $filename);
$check = in_array($extension, $allowedfileExtension);
$fullpath = $filename . '.' . $extension ; // adding full path
if ($check) {
// removing 2nd loop
$file->move('storage/photos', $fullpath); // you should include extension here for retrieving in blade later
$img = new AdsPhoto;
$img->ad_id = $ad->id;
$img->filename = $filename;
$img->save();
}
} else {
echo '<div class="alert alert-warning"><strong>Warning!</strong> Sorry Only Upload png , jpg , doc</div>';
}
}
return redirect('/home')->with('success', 'ad + image created');
}
From the documentation, if you want to put your file on storage instead of on public folder you need to put these few lines of code as below in the your controller class
<?php
...
use Illuminate\Support\Facades\Storage;
...
class YourController extends Controller{
...
// Automatically generate a unique ID for file name...
Storage::putFile('photos', new File('/path/to/photo'));
...
}
This command will put your file into storage folder

How to upload image from one project to another project laravel

I have two laravel project i use code in my Myfirstproject to upload to Mysecondproject public\src\img\upload directory.
I try these code in Myfirstproject:
if ($request->hasFile('images')) {
$destinationPath='Mysecondproject\public\src\img\upload';
if ($files = $request->file('images')) {
foreach ($files as $file) {
$name = $file->getClientOriginalName();
$file->move($destinationPath, $name);
$images[] = $name;
}
}
}
But it's not working, any solution for these?
Please try absolute path in $destinationPath as C:\Mysecondproject\public\src\img\upload or D:\Mysecondproject\public\src\img\upload.

PHP foreach($images as $image) not uploading images

I am trying to upload multiple images to my server, however it is not working. It gives me status code 200 but it doesn't upload images.
This is what I do:
if($request->hasFile('post_image')){
$images = $request->post_image;
$i = 0;
foreach($images as $image){
$i++;
$filename = $post->id.'.'.$i.'jpg';
$location = '/var/www/site/html/'.$post->id;
$image->move($location, $filename);
}
}
If I am removing the foreach() then it uploads image but only one.
Why it is not uploading them? What I am doing wrong?
Edit:
Answering my own question here also. The problem was that my key "post_image" had to be "post_image[]" instead.
You forgot to add . before 'jpg' extension in your filename:
Should be like this:
$filename = $post->id.'.'.$i.'.jpg';
I am trying this way upload multiple images:
if(!empty(Input::file('image'))){
$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);
}
$categories = new CategoryType;
$categories->name = Input::get('name');
$categories->image_attachment = $has;
$categories->save();
}
Follow this awnser you can loop on the all uploaded files
Get all files in a foreach loop in Laravel
like $images = Input::file('post_image');
The problem was that my key "post_image" had to be "post_image[]" instead.
$file_ary = array();
$file_count = count($request->file('image') );
$a=($request->file('image'));
$finalArray=array();
for ($i=0; $i<$file_count; $i++) {
$fileName = time().$a[$i]->getClientOriginalName();
$destinationPath = $request->input('path') ;
$finalArray[$i]['image']=$destinationPath.$fileName;
$a[$i]->move($destinationPath,$fileName);
}
return json_encode($finalArray);

Zend addFilter rename single file only

I have an upload form that has two file input's.
I want to rename the files so that each have a unique name. Here is what I have in my Controller
public function mainAction()
{
$upload = new Zend_File_Transfer();
$files = $upload->getFileInfo();
foreach ($files as $file => $info) {
$upload->addFilter('Rename', uniqid($file.'_').'.csv', $file);
}
$upload->receive();
}
Even though I have specified the file as the last paramter in setFilter, it renames both files at the same time so that they end up with the same name.
I figured out how to do it.
This is the form:
<input type="file" name="one">
<input type="file" name="two">
this goes in the controller
$renamefile1 = new Zend_Filter_File_Rename(array(
'target' => $path.'/file1.csv', // path to file
'overwrite' => true
));
//rename file 2 to file2
$renamefile2 = new Zend_Filter_File_Rename(array(
'target' => $path.'/file2.csv', // path to file
'overwrite' => true
));
$names = $upload->getfileName();
$file1 = $renamefile1->filter($names["one"]);
$file2 = $renamefile2->filter($names["two"]);

Categories