Not getting any data from api controller into vue component - laravel

I have a component in vue 3 named index which gets the user form data and passes it onto api controller in laravel.
async submitForm() {
try {
await axios.post(
"/api/show",
{
firstname: this.form.firstname,
email: this.form.email,
},
);
} catch (error) {
console.error("error");
}
},
and I'm trying to fetch the data sent into the controller via following method onto another component named show and all I'm getting is empty string and I don't understand the reason. Any guide would be really appreciated.
loadProductDetails() {
axios.post("api/show")
.then(({data}) => (this.products = data));
},

Solved the issue. It was because I was trying to get response from two different routes but the first one was already fetching the post response data and second one was returning the empty string and replacing the data I already recieved from the response.
try {
axios
.post("/api/show", {
firstname: this.form.firstname,
email: this.form.email,
selectedAnswer: this.form.selectedAnswer,
selectedCategory: this.form.selectedCategory,
})
.then((res) => {
localStorage.setItem("show", JSON.stringify(res.data));
});
} catch (error) {
console.error("error");
}
Simply saving the response data into local storage and getting it from another component solved the issue.
loadProductDetails() {
this.products = JSON.parse(localStorage.getItem('show'));
}

Related

How to POST correctly a form that have data and files with VueJS, Axios and Laravel?

I am posting here as a beginner of VueJS and Laravel. I am stuck with a problem that I can't fix by myself after hours of search.
I would like to know how correctly send and get back the inputs of a form (complex data and files).
Here is the submit method of the form:
onSubmit: function () {
var formData = new FormData();
formData.append("data", this.model.data);
formData.append("partData", this.model.partData);
if (this.model.symbolFile != null) {
formData.append("symbolFile", this.model.symbolFile);
}
if (this.model.footprintFile != null) {
formData.append("footprintFile", this.model.footprintFile);
}
axios
.post("/api/updatecomponent", formData, {
headers: {
"Content-Type": "multipart/form-data",
},
})
.then((res) => {
// do something with res
// console.log(res);
})
.catch((err) => {
/* catch error*/
console.log(err);
});
},
The variable Data and PartData contains multiple string fields which will be stored in different tables in my database. Example :
Data
{
string Value,
string Tolerance,
string Power
}
Here is the method of the Controller in the server side:
public function updateComponent(Request $req)
{
$data = $req->input('data');
$partData = $req->input('partData');
$symbolFile = $req->file('symbolFile'); // is null if the user did not modify the symbol
$footprintFile = $req->file('symbolFile'); // is null if the user did not modify the footprint
// etc...
}
I am able to get the files, everything work for that and I can store and read them :)
But, the problem is that I am unable to get back properly my Data or PartDat.
When I do :
dd($partData);
I got as result in the console:
"[object Object]"
I am almost sure that I don't use correctly the FormData but after hours of search, I can't find the good way I should gave the Data and PartData to the FormData.
My code was working well for Data and PartData until I add FormData to support the file upload :(
Thank you for your help :)
Here my working code:
Client side:
var formData = new FormData(); // create FormData
formData.append("subcat", this.subcategory);// append simple type data
formData.append("data", JSON.stringify(this.model.data));// append complex type data
axios // send FormData
.post(url, formData, {
headers: {
"Content-Type": "multipart/form-data",
},
})
.then((res) => {
// do something with res
// console.log(res);
})
.catch((err) => {
/* catch error*/
console.log(err);
});
Server side:
public function createComponent(Request $req)
{
$subcategory = $req->input('subcat'); // get the input parameter named 'subcat' (selected subcategory)
$data = json_decode($req->input('data'), true); // get the input, decode the jason format, force to return the result as an array
}
I hope it will help other peoples :)
Simple solution
let data = new FormData();
data.append('image',file_name.value);
_.each(form_data, (value, key) => {
data.append(key, value)
})
console.log('form data',data);
Now you can get data in laravel controller like:
$request->title
$request->description
$request->file

Cashier throws error "A parameter provided in the URL (payment_method) was repeated as a GET or POST parameter." while adding payment method

I am using cashier for stripe in laravel 7, getting this error while adding payment method.
A parameter provided in the URL (payment_method) was repeated as a GET or POST parameter. You can only provide this information as a portion of the URL.
I am passing payment intent to the blade like this,
'intent' => $user->createSetupIntent()
In js,
cardButton.addEventListener('click', async (e) => {
e.preventDefault();
const { setupIntent, error } = await stripe.confirmCardSetup(
clientSecret, {
payment_method: {
card: cardElement,
billing_details: { name: cardHolderName.value }
}
}
);
if (error) {
// Display "error.message" to the user...
} else {
send('save', false, {
data: {
payment_method: setupIntent
}
});
// The card has been verified successfully...
}
});
then adding
$paymentMethod=$request['payment_method'];
$user->updateDefaultPaymentMethod($paymentMethod);
Can anyone help me find out what is the issue.
It was a fault from my side,I passed complete setup intent instead of payment method in updateDefaultPaymentMethod.
I need to set data as payment_method: setupIntent.payment_method

laravel (with vue and vuex) overriding sendResetLinkEmail but can't pass the data to the api controller

I'm creating forgot password on my web application using laravel (with vue and vuex). I found a good tutorial (https://codebriefly.com/vue-js-reset-password-laravel-api/). I try to apply vuex on this tutorial but it not works.
Accrording to the tutorial
<script>
export default {
data() {
return {
email: null,
has_error: false
}
},
methods: {
requestResetPassword() {
this.$http.post("/reset-password", {email: this.email}).then(result => {
this.response = result.data;
console.log(result.data);
}, error => {
console.error(error);
});
}
}
}
</script>
I apply Vuex
ForgotPassword.vue
methods: {
...mapActions(["requestResetPassword"]),
request() {
this.requestResetPassword({
email: this.email
})
.then(response => {
toast.fire({
type: "success",
title: "Password reset email sent"
});
this.$router.push({ name: "home" });
})
.catch(error => {
console.error(error);
});
});
}
Vuex action that i created
requestResetPassword(data){
return new Promise((resolve,reject) => {
axios.post('/reset-password',{
email: data.email
})
.then(response =>{
resolve(response)
})
.catch(error =>{
reject(error)
})
})
}
The Api that handle
public function sendPasswordResetLink(Request $request)
{
return $this->sendResetLinkEmail($request);
}
When I input the email address for sending password reset link, the error shows up and it says:
message: The given data was invalid.
email :The email field is required.
I test the API using postman and it works
I check the input field to see if it was empty, but it turns out the input field was not empty
Is there a way to apply vuex on this tutorial ? thanks
In Postman, you are putting the email field as a param, not as serialized data in the body. The vue-resource package's post method sets the data passed to it as the body, not as URL parameters. Either add the email to the request parameters, or in your API, make sure you grabbing data from the request body and not URL parameters.

How to handle Apollo Graphql query error in Vue.JS?

I am using Vue.js with Vue-Apollo and trying to fetch shared member list using query. I am using the graphQL service in backend.
I am using apollo 'error' function to handle GraphQL error. When the request is made with invalid input, I can see the errors in the network tab, I can see the JSON for the custom errors messages. But I can't console the errors in 'error' function.
Here is the apollo query that is used to fetch shared member list -
apollo: {
sharedMembers: {
query: gql`
query item($uuid: ID) {
item(uuid: $uuid) {
...itemTemplate
members {
...member
permission
}
}
}
${ITEM_TEMPLATE}
${MEMBER}
`,
variables() {
return {
uuid: this.$route.params.uuid,
}
},
update(data) {
return data.item.members
},
error(error) {
console.log('errors', error)
}
},
},
The network response I got -
network_error
Using graphQLErrors
You could get the errors by looking in the error object for graphQLErrors:
error(error) {
console.log('errors', error.graphQLErrors)
}
or
error({ graphQlErrors }) {
console.log('errors', graphQLErrors)
}
Using apollo-error-link
You can use apollo-error-link to help solve your problem if the above doesn't work, docs here.
Here's an example from the docs and I added to it in the networkErrors section to show what you can do to edit the error message you see in your error block, or catch block if its a mutation.
import { onError } from "apollo-link-error";
const link = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors)
graphQLErrors.map(({ message, locations, path }) =>
console.log(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
),
);
if (networkError) {
// Add something like this to set the error message to the one from the server response
networkError.message = networkError.result.errors[0].debugMessage
console.log(`[Network error]: ${networkError}`)
};
});
And then in your code:
error(error) {
console.log('error-message', error.message)
}
The console should then log your debugMessage from the server.
unfortunately i couldn't find out how i'd handle errors in such of graphql method call, but as an option you could provide onError method to ApolloClient constructor options. first argument is the error object. hopefully it may help. like so..
const apolloClient = new ApolloClient({
uri: 'http://localhost:4000',
onError(err) {
console.log(err)
},
})

TypeError: Cannot read property 'props' of undefined in react-redux

I am using axios to create a restful api in my project.Based on the server response I am trying to dispatch an action.
restful api code
handleSubmit(e) {
console.log("form submit");
e.preventDefault();
const forms=new FormData(e.target);
axios.post("http://localhost:8080/reactLogin",forms).then(res=> {
console.log(res.data);
this.props.loginSubmit(res.data);
}).catch(err=>console.log(err))
}
code to dispatch action in react-redux
const mapStateProps=(state) => {
return {
userLogin:state.loginDetails
}
}
const mapDispatchProps=(dispatch) => {
return {
loginSubmit:(data) => {
console.log(data);
if(data.status==1) {
dispatch(loginSuccess(data.data[0]));
}
else {
dispatch(loginFail(data))
}
},
emailInputBorder:(data) => {
dispatch(emailBorder(data));
},
passwordInputBorder:(data) => {
dispatch(passwordBorder(data));
}
}
}
export default connect(mapStateProps,mapDispatchProps)(Login)
when i trying to dispatch an action in my restful api response it shows following error
TypeError: Cannot read property 'props' of undefined
what the issue here is?
If you are using a functional component, you can access the props directly without using the this keyword.
Access the method with something like props.loginSubmit directly.
Since I am not able to view your entire file, this is just a pre-assumption. It would be helpful if you could share the entire code.

Resources