Upload Multiple images in Laravel using Vue.js - javascript

I'm trying to upload image using vue.js in Laravel for that i'm using this link
https://jsfiddle.net/b412ruzo/
to upload image using vue.js and when i submit the form i'm getting following image in files array
now issue is that i cannot get this file array in laravel controller
when i print
$request->file('files')
in my controller i am getting null.
and when i print $request->input('files') this is the result, an empty array
Any help regarding this issue is highly appreciated.
Code Snippet :
data() {
return {
rawData: [],
formData: new Form({
files:[],
})
..
const header = {
Authorization: "Bearer " + this.token,
};
this.formData
.post(APP_URL + `/api/post`, { headers: header })
.then((response) => {
}

not sure you can send ajax request via this.formData.post
try this
new Vue({
el: "#app",
data() {
return {
option: {
maxFileCount: 3
},
files:[],
rawData: [],
}
},
methods: {
loaddropfile: function(e) {
e.preventDefault()
e.stopPropagation()
alert('ok')
console.log(e)
},
openinput: function() {
document.getElementById("vue-file-upload-input").click();
},
addImage: function(e) {
const tmpFiles = e.target.files
if (tmpFiles.length === 0) {
return false;
}
const file = tmpFiles[0]
this.files.push(file)
const self = this
const reader = new FileReader()
reader.onload = function(e) {
self.rawData.push(e.target.result)
}
reader.readAsDataURL(file)
},
removeFile: function(index) {
this.files.splice(index, 1)
this.rawData.splice(index, 1)
document.getElementById("vue-file-upload-input").value = null
},
upload: function() {
alert('Check console to see uploads')
console.log(this.files)
axios.post(`${APP_URL}/api/post`,{files:this.files},{ headers: header })
.then((response) => {});
}
},
mounted(){
}
})
it will send your form data to files key so you can get all the files via $request->file('files')

Related

How to pass data from vue component to view(HTML) in laravel

I'm trying to pass data from vue component to blade file. I try to create props but it's didn't work for me. Is it any possible to pass the object to props to get the data? I'm new laravel. I want to pass data which subject, message, days, condition and module name to blade file(view).
I kept searching for this but couldn't find an answer that will make this clear.
Thanks!
blade.php
<div id="app">
<email-component
email_edit_route="{{ route('havence.automail.edit',['id'=>$mailTemplates->id]) }}"
>
</email-component>
</div>
Vue.js
<script>
import Vue from 'vue'
import axios from 'axios'
import MarkdownIt from 'markdown-it'
import ClassicEditor from '#ckeditor/ckeditor5-build-classic';
var msg_editor;
const md = new MarkdownIt({
linkify: true
})
export default {
props: ['email_creation_link', 'email_index_route', 'email_edit_route','conditions','modules'],
components: {
},
data() {
return {
template: {
subject: '',
message: '' ,
days: '',
condition_id: 1,
},
options:[
{
display:'Client Name',
actual:'Client name'
},
{
display:'Joined Date',
actual:'Joined date'
},
{
display:'Module Name',
actual:'Module name'
},
{
display:'Last Seen',
actual:'Last seen'
},
],
showName: false,
}
},
mounted(){
var self = this;
ClassicEditor
.create(document.querySelector( "#msg"),
{
})
.then(editor => {
msg_editor = editor;
editor.model.document.on( 'change:data', () => {
self.template.message = msg_editor.getData();
});
})
.catch(error => {
console.error(error);
})
},
methods: {
//Drag items
dragstart: function(item, e){
this.draggingItem = item;
e.dataTransfer.setData('text/plain', item.actual);
},
dragend: function(item,e) {
e.target.style.opacity = 1;
},
dragenter: function(item, e) {
this.draggingItem = item;
},
//content
replaceVariables(input)
{
let updated = input
return updated
},
//hidecontent
showHide: function(e)
{
console.log("Show "+e.target.value+ " fields")
this.showName = e.target.value !== ''
},
fetch()
{
//request data
axios.get(this.email_index_route,this.template)
.then((res) => {
this.template = res.data.template;
})
},
save()
{
//save data to db
axios.post(this.email_index_route, this.templates)
.then((res) => {
alert('Mail sent successfull!')
})
},
addToMail: function(type, text)
{
if (type == 'message') {
this.template.message += text;
msg_editor.setData(this.template.message);
}
},
//user name replace
replaceVariables() {
return this.replaceVariables(this.options || '')
},
}
}
</script>
Quick solution. : why not store data in local storage and fetch it from laravel blade ?
Next solution: you can fire global event from vue and listen on laravel blade .
why dont you send the data through ajax post call and get the data from the controller ?
then pass the data object to blade template.

Unable to update existing document in Firebase using VUE

I have never used Firebase before this is my first stab at it using Vue.
I have a setup Firebase using Realtime Databas and set up my project so I can post using the below code in my .vue file
this.$http.post('https://MY_PROJECT_NAME.firebaseio.com/posts.json', {
title: this.blog.title,
body: this.blog.content,
createdDate: this.$options.filters.fullMthDate(this.blog.publishDate),
author: this.blog.author,
active: true,
closedDate: null,
}).then((response) => {
this.$blogAdded = true;
this.loading = false;
this.$router.push('/');
}).catch((error) => {
console.log(error);
});
The thing I can't seem to find an answer to is how to then update this document when needed (e.g. user deletes an item, I want 'active' to become false)
I went for the above code as I was using net ninjas tutorials who set FireBase up this way.
I then do a get to list all items using below in my main component
this.$http.get('https://MY_PROJECT_NAME.firebaseio.com/posts.json').then(function(data) {
return data.json();
}).then(function(data) {
var blogsArray = [];
for (let key in data) {
const date = new Date(data[key].createdDate);
const todaysDate = new Date();
if (date <= todaysDate) {
data[key].id = key
blogsArray.push(data[key])
}
}
this.blogs = blogsArray;
this.loading = false;
});
And this displays them on my site
When the user clicks the tile they go to a page where they can 'Delete/Cancel' the post and it's here I am stuck. Below is the code I am using for displaying the selected item
data() {
return {
id: this.$route.params.id,
blog: {},
loading: false,
closeModal: false,
showModal: false
};
},
beforeMount() {
this.loading = true;
},
created() {
this.$http.get('https://MY_PROJECT_NAME.firebaseio.com/posts/' + this.id + '.json').then(function(data) {
return data.json();
}).then(function(data) {
this.blog = data;
this.loading = false;
});
},
methods: {
showCloseBlogModal() {
console.log(this.blog)
VueEvent.$emit('show-delete-blog-modal', this.blog);
}
}
Then when the modal is displayed I get the following in the console.log
I need to update the 'active' value to false when they click 'Yes' using the below
methods: {
deleteBlog() {
// CODE HERE WHEN CLICK 'YES' TO CANCEL
}
}

How to call a function inside a vue npm package?

What I'm trying to do is to display and modify the images that the car has "in my case", so I used the vue-upload-multiple-image package to save the images and went well, but when I call back these images to the same package I got stuck.
I convert the images that has been stored to base64 now what I want is the list of images go to specific function inside that package, so it will display the images when I try to update the car.
This is the function I want to call:
createImage(file) {
let reader = new FileReader()
let formData = new FormData()
formData.append('file', file)
reader.onload = e => {
let dataURI = e.target.result
if (dataURI) {
if (!this.images.length) {
this.images.push({
name: file.name,
path: dataURI,
highlight: 1,
default: 1,
})
this.currentIndexImage = 0
} else {
this.images.push({
name: file.name,
path: dataURI,
highlight: 0,
default: 0,
})
}
this.$emit(
'upload-success',
formData,
this.images.length - 1,
this.images,
)
}
}
reader.readAsDataURL(file)
},
The Function inside this file
I tried to console.log the function normally it outputs undefined,
I think of props but how it gonna help me.
mounted(){
console.log(this.createImage);
What I want is just to call this function inside my editcar component and sent to it the converter images.
Thank you for helping me and read the this far.
I Found the solution of the problem: in the doc there is dataImages prop. I use it like this:
<div class="form-group m-form__group">
<vue-upload-multiple-image
#upload-success="uploadImageSuccess"
#before-remove="beforeRemove"
#edit-image="editImage"
:dataImages="images"
></vue-upload-multiple-image>
</div>
And it must the images base64 so here is the function the the data.
data() {
return {
images :[],
}
},
mounted() {
this.ConvertImages();
},
This is methods:
methods: {
ConvertImages() {
let images = this.car.images
let image = this.images
for (var i = 0; i < images.length; i++) {
this.toDataURL(images[i].path, function(dataURL) {
image.push({
path: dataURL,
})
})
}
},
toDataURL(url, callback) {
var xhr = new XMLHttpRequest()
xhr.onload = function() {
var reader = new FileReader()
reader.onloadend = function() {
callback(reader.result)
}
reader.readAsDataURL(xhr.response)
}
xhr.open('GET', url)
xhr.responseType = 'blob'
xhr.send()
},
}, //END OF METHODS

Cancel/Abort Axios Post on Vue Component

I have got a Vue Component which has a list of values, when you select these values this changed the selected array, which in tern is posted to an endpoint.
I have an issue if the user spam clicks these values, as an individual post is created for each change, I want it so that if the user selects another item then the currently pending post is cancelled, so then the new value is posted and updates the endpoint with both the selected items.
However i'm having an issue with aborting the current axios request, I have provided the code below. There are no errors, the request simply doesn't cancel.
export default {
props: {
endpoint: {
default: '',
type: String
},
parameters: {
default: null,
type: Object
}
},
data: () => ({
loaded: false,
selected: [],
save: [],
data: [],
cancel: undefined
}),
methods: {
update() {
const self = this;
let params = this.parameters;
params.data = this.selected;
this.$root.$emit('saving', {
id: this._uid,
saving: true
});
if (self.cancel !== undefined) {
console.log('cancel');
this.cancel();
}
window.axios.post(this.endpoint + '/save', params, {
cancelToken: new window.axios.CancelToken(function executor(c) {
self.cancel = c;
})
}).then(() => {
this.$nextTick(() => {
this.loaded = true;
this.$root.$emit('saving', {
id: this._uid,
saving: false
});
});
}).catch(function (thrown) {
if (window.axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
}
});
}
}
}
I have got a global instance of Axios created on my Vue Application.

How to fetch data from server in vue js?

I am trying to fetch data from the server using Vue + Vuex + Vue resource.On button click I want to hit Http request and show in list format .I tried like that.Here is my code
https://plnkr.co/edit/EAaEekLtoiGPvxkmAtrt?p=preview
// Code goes here
var store = new Vuex.Store({
state: {
Item: []
},
mutations: {
getItems: function (state) {
}
},
actions: {
fetchData:function (context) {
this.$http.get('/data.json', function(v1users)
{
// this.$set('v1_user',v1users);
});
}
}
})
var httprequest = Vue.extend({
"template": '#http_template',
data: function () {
return {
items: store.state.Item
}
},
methods: {
fetchData: function () {
store.dispatch('fetchData')
},
}
})
Vue.component('httprequest', httprequest);
var app = new Vue({
el: '#App',
data: {},
})
;
any udpdate?
Try using Vue.http.get instead of this.$http.get.
Vuex doesn't have access to $http directly from instance.

Categories