Vue Custom input file component could not be submitted correctly - laravel-5

I have a component for browsing files which I use to select the file I want to upload.
Here is my component:
<template>
<label class="file-select">
<div class="select-button">
<span v-if="value">Selected File: {{value.name}}</span>
<span v-else>Select File</span>
</div>
<input type="file" #change="handleFileChange"/>
</label>
</template>
<script>
export default {
props: {
value: File
},
methods: {
handleFileChange(e) {
this.$emit('input', e.target.files[0])
}
}
}
</script>
Here is how I used my component:
<p>Select Image: <bim-fileinput v-model="file"></bim-fileinput></p>
Here is how I submit the file with axios:
submit: function(){
console.log(localStorage.getItem('token'));
axios.post('/api/employees', {
picture: this.file,
}, { headers: { Authorization: 'Bearer '.concat(localStorage.getItem('token')) }, 'Content-Type': 'multipart/form-data' })
.then(response => {
router.push({ name: "IndexEmployees"});
}).catch(error => {
console.log(error.message);
});
}
After submitting, in controller I get the picture attribute but as an empty array.
so I tried to print it using console.
console.log('File '+ JSON.stringfy(this.file))
I got File {}
as an empty object.
So I need to figure out where is the problem in my code or how to make it correctly.
Thanks in advance.

this.file is instance of File, it's always as {} when json encode.
The problem in axios, you must use FormData to send file.
const formData = new FormData();
formData.append('picture', this.file);
axios.post('/api/employees', formData, {
headers: {
'Content-Type': 'multipart/form-data',
// ...
}
}) // ...

Related

Shopify Ajax API, Alpine JS, add user selected options to cart using Ajax

I am building this Build A Box section where a user can select various items that make up 1 product. I'm having trouble getting items into the cart.
UPDATE:
Current state is can add the hard coded main product in formData I did this first to get addToCart started. It’s adds the main product but does not redirect to cart page. If you change url in browser to /cart its in there.
I need to figure out 2 things.
1 how to redirect to cart page after firing addToCart()
2 How to add user selected items as 1 product to cart not variants.
See Logs
I can select elements and push into an array in my x-data component. The data looks like this:
[
{img_string: 'https://cdn.shopify.com/s/files/1/0695/7495/1222/files/Barky.webp?
v=1672528086&width=150', title: 'Barky', id: 'selected_item-1'},
{img_string: 'https://cdn.shopify.com/s/files/1/0695/7495/1222/files/Barky.webp?
v=1672528086&width=150', title: 'Barky', id: 'selected_item-1'}
]
For my latest iteration, I just hard coded the variant id & a quantity. Still have to figure out how to get all the selected items into the cart.
UPDATE: I added preventDefault filter to Alpine addToCart() call now it does not redirect but if you change url in browser to /cart the hard coded main product is in there.
<div x-data="items: []">
<div
x-data="
{
qty: 1,
addToCart(){
let formData = {
'items': [{
'id': 44202123100470,
'quantity': 1
}]
};
fetch(window.Shopify.routes.root + 'cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
})
.then(response => {
console.log(response)
return response.json();
})
.catch((error) => {
console.error('Error:', error);
});
}
}
"
class="tw-mt-12 tw-flex tw-flex-col tw-p-auto tw-bg-brandText tw-opacity-80"
>
<div class="tw-p-8">
<h2 class="tw-mb-4 tw-text-white">Your Selections</h2>
{% assign product_form_id = 'product-form-' | append: section.id %}
{%- form 'product',
product,
id: product_form_id,
class: 'form',
novalidate: 'novalidate',
data-type: 'add-to-cart-form'
-%}
<input
type="hidden"
name="id"
value="{{ product.selected_or_first_available_variant.id }}"
disabled
>
<input type="hidden" name="quantity" x-model="qty" value="1">
<div class="product-form__buttons">
<button
type="add"
#click="addToCart()"
:class="full_box ? 'tw-bg-ctaColor' : ''"
class="tw-bg-white tw-text-brandText tw-flex tw-justify-center tw-py-4 tw-px-6 tw-rounded-full tw-font-bold"
>
<p class="" x-show="!full_box">
<span x-text="items_selected" class="tw-mr-2"></span><span class="tw-mr-2">of</span
><span class="tw-font-bold" x-text="box_size"></span><span class="tw-ml-2">Selected</span>
</p>
<p x-show="full_box" class="">Add to cart</p>
</button>
</div>
{%- endform -%}
</div>
</div>
The way I solved the redirect issue was to use the Location API add location.href="/cart" in the success promise of the Ajax call.
fetch(window.Shopify.routes.root + 'cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
})
.then(response => {
console.log(response)
return response.json();
})
.then((data) => {
location.href = '/cart';
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
To solve the issue of how to get all selected items into the cart. I mapped over the items array of objects and returned an array of strings. Then I assigned to a variable selectedItems and called toString()
In the properties key of formData I added a value of selectItems to Box Items key. Kinda ugly at the moment no spaces in string. Definitely need to refactor this. Any feedback would be Super Cool 🏄‍♂️
<div
x-data="
{
addToCart(items, id){
let itemsToAdd = items.map((item) => {
return item['title'];
})
let selectedItems = itemsToAdd.toString()
let formData = {
'items': [{
'id': id,
'quantity': 1,
'properties': {
'Box Items': selectedItems,
}
}]
};
fetch(window.Shopify.routes.root + 'cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
})
.then(response => {
console.log(response)
return response.json();
})
.then((data) => {
location.href = '/cart';
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
reset()
}
}
"
class="tw-mt-12 tw-flex tw-flex-col tw-p-auto tw-bg-brandText tw-opacity-80"
>...</div>

Allow HTML Tags Through Axios Request from Vue to Laravel Controller

I have a text area as below:
<textarea class="from-control" name="body" id="body" v-html="pageForm.body" v-model="pageForm.body" rows="5" style="width:100%"></textarea>
Script:
<script>
export default {
components: {},
data() {
return {
pageForm: new Form({
body: '',
}),
};
},
props: [],
mounted() {
},
methods: {
update() {
let loader = this.$loading.show();
this.pageForm.patch('/api/frontend/google-map/')
.then(response => {
toastr.success(response.message);
loader.hide();
})
.catch(error => {
loader.hide();
helper.showErrorMsg(error);
});
},
}
}
</script>
I am sending an <iframe> from the <textarea> via axios patch request as <iframe src="some url"></iframe>
But in the laravel controller I receive $request->body = ""
Any ideas how do I achieve this?
Note:Form binding is working fine, but get empty value in Laravel Controller

Trying to get a single data and display in a vue component, but nothing is displaying

I am using Laravel 5.8 + Vue.js in my project.
Trying to get a single data from a controller but nothing is displaying.
I added the 12345 in the component to check if the component is working, 12345 is showing well.
controller
public function getSingleData($idx)
{
$paymentData = PaymentData::where('idx', $idx)->first();
return view('paydetail')->with('paymentData', $paymentData);
}
router
Route::view('/paylist', 'paylist')->name('paylist.view');
Route::get('/paylist/data', 'PaymentController#getPaymentData')->name('paylist');
Route::get('/paydetail/{idx}', 'PaymentController#getSingleData')->name('paydetail');
blade
#extends('layouts.default')
#section('content')
<div class="container">
<paydetail :idx="{{ $paymentData->idx }}"></paydetail>
app.js
Vue.component('paydetail', require('./components/Paydetail.vue').default);
Paydetail.vue
<template>
<div>
<h2>12345</h2>
<div v-for="val in paymentData">
<h2>{{ val.app_name }} </h2>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
props: [ 'idx' ],
data() {
return {
paymentData: [{}],
}
},
created() {
this.paymentData = this.getPayDetailData();
console.log(this.idx);
console.log("here");
},
methods: {
getPayDetailData() {
axios({
method: 'GET',
url: '/paydetail/'+ this.idx
}).then(
response => {
console.log(response)
return response
},
error => {
console.log(error)
}
)
},
},
}
</script>
The result of console.log(response) is weird. It shows the whole html document which I don't understand at all.
It shows like this.
{data: "<!DOCTYPE html>↵<html>↵ <head>↵ <meta ch…>↵<!-- For Datatable -->↵↵↵ </body>↵</html>↵", status: 200, statusText: "OK", headers: {…}, config: {…}, …}
What did I wrong here?

Laravel show required error message when submitting the form with image and data both

About
I am submitting the image with plain text using vue.js and Laravel 5.8.
Error Details
When I submit the data using axios, it gives validation error message that product name is required. I am submitting both name and image. Everything works when I disable the code to submit image.
Request Header - Please click the image to view more details clearly
Payload - Please click the image to view more details clearly
Html
<template>
<div>
<input name="Product Name" type="text" v-model="saveForm.product_name">
<input type="file" accept="image/*" name="product_image" />
<button type="button" #click="store()">Save</button>
</div>
</template>
Script
<script>
export default {
data() {
return {
saveForm: {
product_name: '', product_image: null
}
};
},
methods: {
store() {
var config = {
headers : {
'Content-Type': 'multipart/form-data', 'processData': false
}
};
var fileData = new FormData();
fileData.append("product_image", this.saveForm.product_image);
fileData.append("product_name", this.saveForm.product_name);
axios.post("my route", this.saveForm, config).then(response => {
if(response.data.Status) {}
})
.catch(error => { //console.log(error);
});
}
}
}
</script>
Laravel Controller Action Method
public function Create(CreateProductRequest $request) {
//Code here
}
Laravel Request class
class CreateProductRequest extends Request
{
public function wantsJson() {
return true;
}
public function rules() {
return [
'product_name' => 'required',
'product_image' => "image|mimes:bmp,png,jpg,gif,jpeg"
];
}
}
Ok, let's review your code step by step.
1) You need add "boundary" to header. It's small important, but needed for the server.
headers: {
"Content-type":
"multipart/form-data; charset=utf-8; boundary=" +
Math.random()
.toString()
.substr(2),
processData: false,
Accept: "application/json"
}
2) Why do you prepare data through "new FormData()", but sending with "this.saveForm"? Correct code:
axios.post("my route", fileData, config)
.then(response => {
if (response.data.Status) {}
})
.catch(error => { //console.log(error);
});
3) When you do everything as I said above, you will get an error with the image, because you didn't pass it. I added functionality to send images.
summary:
Html
<div>
<input
name="Product Name"
type="text"
v-model="saveForm.product_name"
>
<input
type="file"
accept="image/*"
name="product_image"
#change="uploadImage"
/>
<button
type="button"
#click="store()"
>Save</button>
</div>
Script
export default {
data() {
return {
saveForm: {
product_name: "",
product_image: null
}
};
},
methods: {
store() {
var config = {
headers: {
"Content-type":
"multipart/form-data; charset=utf-8; boundary=" +
Math.random()
.toString()
.substr(2),
processData: false,
Accept: "application/json"
}
};
var fileData = new FormData();
fileData.append("product_image", this.saveForm.product_image);
fileData.append("product_name", this.saveForm.product_name);
axios
.post("my route", fileData, config)
.then(response => {
if (response.data.Status) {
}
})
.catch(error => {
console.log(error);
});
},
uploadImage(e) {
this.saveForm.product_image = e.target.files[0];
}
}
};

Vue custom v-model value doesn't update the value after getting it from axios get request

I have a component called "TextInput":
<template>
<q-input
v-model="content"
#input="handleInput"
color="secondary"
:float-label="floatLabel" />
</template>
<script>
import { QInput, QField } from "quasar-framework/dist/quasar.mat.esm";
export default {
props: ['floatLabel', 'value'],
data () {
return {
content: this.value
}
},
components: {
'q-field': QField,
'q-input': QInput,
},
methods: {
handleInput(e) {
this.$emit('input', this.content)
}
}
}
</script>
I used this component in another component:
<template>
<card card-title = "Edit Skill">
<img slot="img" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABoAAAAaCAYAAACpSkzOAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAJeSURBVEhLzZVPSFRRGMVnKopI+odghFjWQDD05v8/dGCEaFEhbnwIQQTVol2rCHElQog7lwm6qdy0jBJpWQvBImgTEqGYoKIDYhS4qt9n38Qb5973ni7KA2fuPd937jt35t33JrKvUCqVjmaz2XI8Hm8qFArHmT8KS/ytehk7UqlUHPOzTCbzA36EDroNbsEnQcS/zFjWy5mRy+VuYaxiHIDNWo4wl6ANlb5g/VvfIAw3ZDfQ0dJfWIKi8uE4zil6LuuKon2DEonEMZpL6XT6ipbqsDOIi12EH/AnisViC/MqfK49exCN+xheqWyAN0huNN5FOAnlF/gMh+l3Sp+5b9AUu+tT2QBvEKfwMPMemXPR28wfy7wG3yCaa8lk8rzKBniDgmANkgCa6yqN8AYx3sX/xsB+6TOag2iM0phQaYQ3CL88V+5OUrefOp6byzSq+Xz+jJaM4AC049vEf8GPcv+MQRSn4UOVRnBIcixchfN4v1r4jf4vwmTj9UGIq/BLLBY7oiUj8IyxeEilEWymG88M0yj+WQI7/nQAhV6ac4xdWjKCRXfwzMMR/MMm0nvK+BO+gCvoE7p8G1GK9yguMG4/1TYQdg2f8U3tJdd5YH1M+NrnMFRV7hoE9MhfikpfHMC8xU5Oqg4NNnmWTW7K/5WW/IFZ3lcZlaHBBgfhmMpgYH5Jzk2VocG69/C6ymBglrf3u93+fKxb5aBcUhkM13UPEjTOwu+MtYfwtbatwL8B645yKHB6TrPDNIvlxflJy1bsOagGFpf/SZDcK4JKKq0gpKtSqRxS+b8QifwGm+z/Ksto7VkAAAAASUVORK5CYII=">
<form class="clearfix" slot="form">
<bim-text v-model="skill.name" :floatLabel="input_label"></bim-text>
<q-btn
#click="edit"
icon="save"
size="14px"
color="secondary"
label="Save" />
</form>
</card>
</template>
<script>
import { QBtn } from "quasar-framework/dist/quasar.mat.esm";
import { Card, TextInput } from "../../base";
import router from '../../../routes/routes';
export default {
data: function () {
return {
id: this.$route.params.id,
skill: {
name: ''
},
input_label: 'Skill Name'
}
},
components: {
'card': Card,
'bim-text': TextInput,
'q-btn': QBtn
},
methods: {
edit: function(){
axios.patch('/api/skills/'+this.id, {
name: this.skill.name,
}, { headers: { Authorization: 'Bearer '.concat(localStorage.getItem('token')) } })
.then(response => {
alert('success');
router.push({ name: "IndexSkills"});
}).catch(error => {
console.log('dd');
});
}
},
mounted() {
axios.get("/api/skills/"+this.id, { headers: { Authorization: 'Bearer '.concat(localStorage.getItem('token')) } })
.then(response => {
this.skill = response.data.data;
}).catch(error => {
alert('error')
});
}
}
</script>
<style scoped>
.q-btn{
float: right;
margin-top: 20px;
}
</style>
As you can see, I created an skill object with empty property called name and I made an axios request to get the specified object using its id. In then function of the axios request skill should be updated but what happened was that the v-model still empty.
What would be the problem here? and how can I solve it?
Thanks in advance.
You only assign v-model value (value property) to your content variable on initialization (data() method, which is only called on component initialization). You have no code that can react to value (v-model) change, that would update the content variable.
You should create a watch for value, and then set this.content = this.value again.
PS: Also, try instead of this
this.skill = response.data.data;
do this
this.skill.name = response.data.data.name;

Resources