Laravel + vue: Error message only showing the first letter of the sentence - vue.js

I'm just starting to learn laravel+vue. I was able to follow a tutorial from this yt: https://www.youtube.com/watch?v=JZDmBWRPWlw. Though it seems outdated, I was still able to follow his steps. I'm using the laravel-mix 6.0.6 and vue 2.6.12.
Using inspect element>network, I can see that I'm throwing the correct error message in array.
{"component":"Users\/Create","props":{"app":{"name":"Laravel"},"errors":{"name":"The name field is required.","email":"The email field is required."}},"url":"\/users\/create","version":"207fd484b7c2ceeff7800b8c8a11b3b6"}
But somehow it is not displaying the complete error message. Right now it just show the first letter of the sentence. LOL. Sample error message is: The email field is required and it will just display the letter "T". Below is my Create.vue. Basically it is just a user create form with simple validation.
Create.vue
<template>
<layout>
<div class="container">
<div class="col-md-6">
<div v-if="Object.keys(errors).length > 0" class="alert alert-danger mt-4">
{{ errors[Object.keys(errors)[0]][0] }}
</div>
<form action="/users" method="POST" class="my-5" #submit.prevent="createUser">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" placeholder="Name" v-model="form.name">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" class="form-control" id="email" placeholder="Email" v-model="form.email">
</div>
<div class="form-group">
<label for="name">Password</label>
<input type="password" class="form-control" id="password" placeholder="Password" v-model="form.password">
</div>
<button type="submit" class="btn btn-primary">Create User</button>
</form>
</div>
</div>
</layout>
</template>
<script>
import Layout from '../../Shared/Layout'
export default {
props: ['errors'],
components: {
Layout,
},
data() {
return {
form: {
name: '',
email: '',
password: '',
}
}
},
methods: {
createUser() {
this.$inertia.post('/users', this.form)
.then(() => {
// code
})
}
}
}
</script>
Edit:
I have this error on my console
[Vue warn]: Error in v-on handler: "TypeError: Cannot read property
'then' of undefined"
found in
---> at resources/js/Pages/Users/Create.vue

Your error call is probably getting only the first letter due to [0]. Try to change to:
{{ errors[Object.keys(errors)[0]] }}
Strings can also be read as arrays. If you do this:
$a = "TEST";
echo $a[0];
That would print only T.
That is probably the problem.

Related

testing api sending OPTIONS method and getting 405 error [duplicate]

This question already has an answer here:
FastAPI's RedirectResponse doesn't work as expected in Swagger UI
(1 answer)
Closed 5 months ago.
Im new to vue and nuxt, im using this ones to connect them to my API made with fastapi, and whenever i try to create an account via my API with the vue form i get this error
127.0.0.1:52137 - "OPTIONS /user HTTP/1.1" 405 Method Not Allowed
I've seen that sometimes axios sends an OPTION method to "test" the api if i get it.. But how do i solve this problem ?
Im new to this so do not hesitate to ask me more files/code.
Here is the Post method that im trying to reach and my registration page on VUE.
#app.post("/user", response_model=_schemas.UserBis)
async def create_user(user: _schemas.UserIn, db: _orm.Session = fastapi.Depends(_services.get_db)):
db_user_email = await _services.get_user_by_email(email=user.email, db=db)
if db_user_email:
raise fastapi.HTTPException(
status_code=400, detail="User with that email already exists"
)
db_user_username = await _services.get_user_by_username(username=user.username, db=db)
if db_user_username:
raise fastapi.HTTPException(
status_code=400, detail="User with that email already exists"
)
db_user_pseudo = await _services.get_user_by_pseudo(pseudo=user.pseudo, db=db)
if db_user_pseudo:
raise fastapi.HTTPException(
status_code=400, detail="User with that pseudo already exists"
)
user = await _services.create_user(user=user, db=db)
return _schemas.UserBis(data=user)
VUE:
<template>
<section class="section">
<div class="container">
<div class="columns">
<div class="column is-4 is-offset-4">
<h2 class="title has-text-centered">Register!</h2>
<Notification :message="error" v-if="error"/>
<form method="post" #submit.prevent="register">
<div class="field">
<label class="label">Username</label>
<div class="control">
<input
type="text"
class="input"
name="username"
v-model="username"
required
/>
</div>
</div>
<div class="field">
<label class="label">Pseudo</label>
<div class="control">
<input
type="text"
class="input"
name="pseudo"
v-model="pseudo"
required
/>
</div>
</div>
<div class="field">
<label class="label">Email</label>
<div class="control">
<input
type="email"
class="input"
name="email"
v-model="email"
required
/>
</div>
</div>
<div class="field">
<label class="label">Password</label>
<div class="control">
<input
type="password"
class="input"
name="password"
v-model="password"
required
/>
</div>
</div>
<div class="control">
<button type="submit" class="button is-dark is-fullwidth">Register</button>
</div>
</form>
<div class="has-text-centered" style="margin-top: 20px">
Already got an account? <nuxt-link to="/login">Login</nuxt-link>
</div>
</div>
</div>
</div>
</section>
</template>
<script>
import Notification from '~/components/Notification'
export default {
components: {
Notification,
},
data() {
return {
username: '',
pseudo: '',
email: '',
password: '',
error: null
}
},
methods: {
async register() {
try {
await this.$axios.post('user', {
username: this.username,
pseudo: this.pseudo,
email: this.email,
password: this.password
})
await this.$auth.loginWith('local', {
data: {
email: this.email,
password: this.password
},
})
this.$router.push('/')
} catch (e) {
this.error = e.response.data.message
}
}
}
}
</script>
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
Any non simple POST request triggers a pre flight check (OPTIONS request) to confirm the action is supported. Your API will need to be modified to allow these requests.
I found a slution to my problem here: https://stackoverflow.com/a/66460861/18428648
Allowing all origins solved my problem, just added a few lines of code to my FastAPI API.

How to use VueStripe on vue2 Project?

I added Vue Stripe on my vue2 Project and I have 2 similar errors on my code :
Property 'redirectToCheckout' does not exist on type 'Vue | Element | (Vue | Element)[]'.
Property 'publishableKey' does not exist on type 'CombinedVueInstance<Vue, unknown, unknown, unknown, Readonly<Record<never, any>>>'.
I followed the documentation on their website and everything is similar as their code so I don't know why I have those errors.
Screenshots
Here is my code if you want to check
<template >
<div class="section form-degustation-section" style="padding-top:150px">
<div class="mycontain form-degustation-contain" >
retrouner aux calendrier des soirées
<div class="soiree-text-presentation-contain">
<h1>{{ degustation[0].title }}</h1>
<p>{{ degustation[0].description }}</p>
</div>
<div class="soiree-form-contain">
<h2>Formulaire de réservation</h2>
<div class="w-form">
<div id="wf-form-soirees-degustation" name="wf-form-soirees-degustation" data-name="soirees degustation" action="https://natureetvins.foxycart.com/cart" method="post">
<label for="name">Nom et prénom</label>
<input type="text" class="w-input" maxlength="256" name="name" data-name="Name" placeholder="Ecrivez votre nom et prénom" id="name" data-kwimpalastatus="alive" data-kwimpalaid="1626170679038-0">
<label for="email">Email Address</label>
<input type="email" class="w-input" maxlength="256" name="email" data-name="Email" placeholder="Ecrivez votre adresse email" id="email" required="" data-kwimpalastatus="alive" data-kwimpalaid="1626170679038-1">
<label for="email-2">Téléphone</label>
<input type="text" class="w-input" maxlength="256" name="field" data-name="Field" placeholder="Ecrivez votre numéro de téléphone" id="field" required="" data-kwimpalastatus="alive" data-kwimpalaid="1626170679038-2">
<label for="quantity" >Quantité</label>
<input v-model="lineItems[0].quantity" type="number" class="w-input" maxlength="256" placeholder="Combien de places voulez vous acheter ?" required="">
<div class="w-embed">
<input type="hidden" name="name" value="Name">
<input type="hidden" name="prix" value="Prix">
<input type="hidden" name="image" value="Image">
</div>
<div class="event-cta-contain">
<div>
<stripe-checkout
ref="checkoutRef"
mode="payment"
:pk="publishableKey"
:line-items="lineItems"
:success-url="successURL"
:cancel-url="cancelURL"
/>
<button #click="submit()" class="cta-button w-button">Payer</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script lang="ts">
import { StripeCheckout } from "#vue-stripe/vue-stripe";
import axios from "axios";
import Vue from 'vue';
export default Vue.extend({
components: {
StripeCheckout,
},
data() {
this.publishableKey = "pk_test_51JAWNYJ3Er0D2qeQ9y9P0RXOsZPfxGC9VVour44gRX2NNiP2CBAzV0NECWsupE5WZhybNBT8TX5TDG5XUOHxg8rg00rMplGIhK";
return {
degustation: [{
}],
id_product: this.$route.params.id as string,
loading: false,
lineItems:[
{
price: "price_1JChqzJ3Er0D2qeQ8cZhp2RM",
quantity: 1 ,
}],
successURL: "http://google.fr",
cancelURL: "http://google.fr",
};
},
mounted() {
axios
.get(`http://localhost:3000/api/v1/degustations/${this.id_product}`)
.then((response) => (this.degustation = response.data));
},
methods: {
submit() {
this.$refs.checkoutRef.redirectToCheckout()
},
},
});
</script>
Do I need to import something else or ?
A couple of things are happening here.
First, keep in mind that if you want to access the publishableKey in the template then you should add it in the object that you're returning in the data() function.
Try to do some checking before accessing checkoutRef, try this:
if (this.$refs.checkoutRef) {
this.$refs.checkoutRef.redirectToCheckout()
}

validate form inputs bootstrap4

I have this code in my vue template
<div class="form-row" :class="{'was-validated': this.checkPassword()}">
<div class="col-6">
<label>Password</label>
<input :type="showPassword ? 'text' : 'password'" class="form-control" ref="password" required v-model="password">
<div class="valid-feedback" v-if="!error">
Password match
</div>
<div class="invalid-feedback" v-else>
Password not match
</div>
</div>
<div class="col-6">
<label>Confirm password</label>
<div class="input-group">
<input :type="showPassword ? 'text' : 'password'" class="form-control" ref="passwordCheck" required v-model="passwordCheck" #change="checkPassword()">
<div class="input-group-append">
<button class="btn btn-secondary" #click.prevent="copyToClipboard()"><i class="fas fa-clipboard"></i></button>
</div>
</div>
</div>
</div>
I want to show like the bootstrap4 documentation a green input field if the password matches or a red one if the password aren't matching. I'm trying by adding the was-validated class to the form-row if the demanded method return true but when the view where the password inputs are rendered the two input fields are always red. How I can fix this to give the correct feedback to the user?
Please always share all the relevant parts of the component otherwise, it's hard to tell where the problem resides. Here, you haven't shared your <script> section. Anyway, I guess this should put you on the right track.
<template>
<div class="form-row" :class="{'was-validated': this.checkPassword()}">
<div class="col-6">
<label>Password</label>
<label>
<input :type="showPassword ? 'text' : 'password'" class="form-control" :class="getPasswordClass()"
ref="password" required v-model="password">
</label>
</div>
<div class="col-6">
<label>Confirm password</label>
<div class="input-group">
<label>
<input :type="showPassword ? 'text' : 'password'" class="form-control" :class="getPasswordClass()"
ref="passwordCheck" required v-model="passwordCheck" #input="checkPassword()">
</label>
<div class="input-group-append">
<button class="btn btn-secondary" #click.prevent="copyToClipboard()"><i
class="fas fa-clipboard"></i></button>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
password: null,
passwordCheck: null,
error: true,
showPassword: true,
}
},
methods: {
checkPassword() {
this.error = this.password !== this.passwordCheck;
},
getPasswordClass() {
if (!this.password || !this.passwordCheck) {
return '';
}
return this.error ? 'is-invalid' : 'is-valid'
},
copyToClipboard() {
//
}
}
}
</script>
So, in my opinion, you should only set the dynamic class (is-valid or is-invalid) when both inputs are provided. In this example I've added that to both password and passwordCheck fields but I think it's enough to just apply it to the passwordCheck because that's the one checked against the password.
If you only want to check after user leaves the field you could adjust the code like this:
In the template remove:
:class="{'was-validated': this.checkPassword()}"
And update:
#blur="checkPassword()
In the data() add:
blurred: false,
In the methods update:
methods: {
checkPassword() {
this.blurred = true;
this.error = this.password !== this.passwordCheck;
},
getPasswordClass() {
if (!this.blurred) {
return '';
}
return this.error ? 'is-invalid' : 'is-valid'
},
...
}

Add invalid class to form-group using VueValidate to bootstrap CSS

How to add invalid class to form-group if the validation fails on input. By default VueValidate adds to the input.
<div class="form-group">
<label for="mobile" v-bind:class="{'text-danger': errors.has('mobile')}">Mobile</label>
<input type="text" v-validate="validation.mobile" class="form-control" v-model="user.mobile" name="mobile" id="mobile" />
<span class="invalid-feedback">{{ errors.first('mobile') }}</span>
</div>
Currently i am using v-bind:class="{'text-danger': errors.has('mobile')}" on the label and i get red colored label on field error.
If i could add invalid to form-group, it would be better to control with css. Below is my VueValidate Settings
Vue.use(VeeValidate, {
aria: true,
classes: true,
classNames: {
invalid: 'is-invalid'
}
});
You can bind a computed function to check errors and return the div's classes
{
computed: {
formGroupClass: function () {
if (this.error.has('mobile') ){
return ['form-group', 'invalid']
}
return ['form-group']
}
}
}
<div :class="formGroupClass">
<label for="mobile" v-bind:class="{'text-danger': errors.has('mobile')}">Mobile</label>
<input type="text" v-validate="validation.mobile" class="form-control" v-model="user.mobile" name="mobile" id="mobile" />
<span class="invalid-feedback">{{ errors.first('mobile') }}</span>
</div>

Vue 2 - use same form for adding new and editing

I have following template:
<template>
<div>
<form #submit="save">
<div class="field">
<label class="label">Name</label>
<div class="control">
<input class="input" type="text" placeholder="Name" :value="book.title">
</div>
</div>
<div class="field">
<label class="label">Name</label>
<div class="control">
<input class="input" type="text" placeholder="Name" :value="book.author">
</div>
</div>
</form>
</div>
</template>
<script>
export default {
data() {
return {
book : {}
}
},
methods: {
save() {
}
},
created() {
if(this.$store.state.book != 'undefined'){
this.book = this.$store.state.book;
}
},
computed: {}
}
</script>
<style></style>
So far everything works fine if the book is pass with the this.$store.state.book, but if this is not passed the form is failing, with the error message:
** Error in render function: "TypeError: Cannot read property 'title' of undefined"**
I thought that passing the empty object would dynamically bind the book object and auto create the params.
Is it possible to use the same form for both adding new and editing?
I tried your code, and all you have to do is remove the 'quotes' from 'undefined'. Obviously, it's a string as is, and not a js thing.