I cannot upload multiple images in my Laravel + vue js project..
here is my code below
my vue conponent
<form @submit.prevent="addProduct" enctype="multipart/form-data">
<div class="form-group">
<div class="row">
<div class="col-lg-4">
<label for="product_image">Product Image:</label>
</div>
<div class="col-lg-4">
<input type="file" name="pics[]" id="product_image" @change="fieldChange" multiple>
<has-error :form="form" field="product_image"></has-error>
</div>
<div class="col-lg-4">
<img :src="form.product_image" height="70px" width="85px" alt="">
</div>
</div>
</div>
</form>
i Used FormData to upload images
data: function(){
return{
attachment:[],
imageForm : new FormData,
}
},
methods:{
fieldChange(e){
let selectedFiles = e.target.files;
if (!selectedFiles.length) {
return false;
}
for(let i=0;i<selectedFiles.length;i++){
this.attachment.push(selectedFiles[i])
}
console.log(this.attachment);
//I checked here ang got image arrays
},
addProduct:function(){
for(let i=0;i<this.attachment.length;i++){
this.imageForm.append('pics[]',this.attachment[i]);
//When I console.log() this line it says undefined
}
axios.post('/save-product',this.form,this.imageForm).then((response)=>{
toastr.success('Product Info Added Successfully','Success!');
}).catch((error)=>{
})
},
}
my controller here...here I find this error
public function store(Request $request)
{
$uploadedFiles = $request->pics;
foreach ($uploadedFiles as $file) {
$file->store(public_path('uploads/products'));
}
return response()->json(['status'=>'success'],200);
}
status says 500 error...and in my network I got that error...And says Invalid argument supplied for foreach().
this is my full part of data..
data: function(){
return{
form: new Form({
product_name:null,
product_color:null,
publication_status:1,
category_id:'',
brand_name:null,
product_price_regular:null,
product_price_discount:null,
product_quantity:1,
short_description:null,
long_description:null,
user_name:'Admin',
// product_image:[],
}),
attachments:[],
imageForm : new FormData,
}
},
please see this part when I do this other fields saved in database but images do not save... and if i do not add these fields images are saved in database
addProduct(){
for(let i=0;i<this.attachments.length;i++){
this.imageForm.append('product_image[]',this.attachments[i]);
}
const data = {
'product_image':this.product_image,'product_name':this.product_name,'product_color':this.product_color,'category_id':this.category_id,'product_price_regular':this.product_price_regular,'product_price_discount':this.product_price_discount,'short_description':this.short_description,'long_description':this.long_description,'user_name':this.user_name,'publication_status':this.publication_status
}
const config= {
headers:{
"Content-Type": "multipart/form-data"
}
}
axios.post('/save-product',data,this.imageForm,config).then((response)=>{
toastr.success('Product Info Added Successfully','Success!');
}).catch((error)=>{
})
},