How to show Array of errors in Vue.js ? Backend Validation with Laravel - laravel

I have some complex data and I want to show the validation error array data in vue file but I can not do it because I have got some data that has an index and showing like contacts.0.name: ["...."].
Please share your opinion how I can show the error.
vue file
<template>
<div>
<form enctype="multipart/form-data" #submit.prevent="handleSubmit">
<div v-for="(contact, index) in contacts" :key="index" class="row">
<div class="col col-md-3">
<div class="form-group mb-4">
<label for="personName">Contact Person Name</label>
<input
id="personName"
v-model="contact.name"
type="text"
class="form-control"
/>
<small> Want to show here the error ? </small
>
</div>
</div>
<!-- Add or Remove button -->
<div class="col col-md-12 text-right">
<div class="row ml-4">
<div v-show="index == contacts.length - 1">
<button
class="btn btn-warning mb-2 mr-2 btn-rounded"
#click.prevent="add"
>
Add More
</button>
</div>
<div v-show="index || (!index && contacts.length > 1)">
<button
class="btn btn-danger mb-2 mr-2 btn-rounded"
#click.prevent="remove"
>
Remove
</button>
</div>
</div>
</div>
</div>
</form>
</div>
</template>
<script>
export default {
data() {
return {
contacts: [
{
name: "",
},
],
errors: [],
};
},
methods: {
handleSubmit() {
let data = new FormData();
data.append("contacts", JSON.stringify(this.contacts));
Request.POST_REQ(data, "/add-institute")
.then(() => {
alert("success");
})
.catch((err) => {
this.errors = err.response.data.errors;
});
},
add() {
this.contacts.push({
name: "",
email: "",
phone: "",
alternate_phone: "",
});
},
remove(index) {
this.contacts.splice(index, 1);
},
},
};
</script>
controller file
public function add_institute(Request $request) {
$request['contacts'] = json_decode($request['contacts'], true);
$request->validate([
'contacts.*.name'=> 'unique:institute_contact_people|distinct',
]);
...rest of code of insert
return response()->json("Success...");
}
Getting Error Response data
errors: {
contacts.0.name: ["The contacts.0.name has already been taken.", "The contacts.0.name field has a duplicate value."]
0: "The contacts.0.name has already been taken."
contacts.1.name: ["The contacts.1.name has already been taken.", "The contacts.1.name field has a duplicate value."]
0: "The contacts.1.name has already been taken."
}

Okay, so your error data is basically an object with array of errors in it.
Pretty much like this
errors: {
'contacts.0.name': [
'The contacts.0.name has already been taken.',
'The contacts.0.name field has a duplicate value.',
],
'contacts.1.name': [
'The contacts.1.name has already been taken.',
'The contacts.1.name field has a duplicate value.',
],
},
For me, it will be better if you could achieve something like this as an error response (an array of objects with errors array in it)
betterErrors: [
{
location: 'contact.0.name',
errors: [
'The contacts.0.name has already been taken.',
'The contacts.0.name field has a duplicate value.',
],
},
{
location: 'contact.1.name',
errors: [
'The contacts.1.name has already been taken.',
'The contacts.1.name field has a duplicate value.',
],
},
],
For me, as of right now, it feels wrong but you can achieve a display of your errors with something like this
<template>
<div>
<div v-for="(error, key) in errors" :key="key">
<hr />
<span v-for="(errorItem, innerKey) in error" :key="innerKey" style="margin-top: 2rem">
{{ errorItem }}
</span>
</div>
</div>
</template>
<script>
export default {
data() {
return {
errors: {
'contacts.0.name': [
'The contacts.0.name has already been taken.',
'The contacts.0.name field has a duplicate value.',
],
'contacts.1.name': [
'The contacts.1.name has already been taken.',
'The contacts.1.name field has a duplicate value.',
],
},
}
},
}
</script>
PS: having a :key with an array looping index is really bad tbh. That's why I do recommend a location field in your error response.

in your controller
$request->validate([
'ClinicName' => 'required|string|min:200',
'Branches.*.BranchName'=>'required|string|min:200'
]);
in your vue3 file, to access the errors which will have keys such as,
'Branches.0.BranchName'
then you can access the above error with for loop similar to this
<p v-if="form.errors['Branches.' + counter + '.BranchName']"
class="mt-2 text-sm text-red-600 dark:text-red-500">
{{ form.errors["Branches." + counter + ".BranchName"] }}
</p>
here the counter can be any counter starting from 0.

Related

Vue.js 3 Uncaught (in promise) TypeError: Cannot convert undefined or null to object

So, I'm trying to fetch my laravel api and already run php artisan serve. After that the error came out and I'm looking to find solution here but I have no idea what's going on.
The error shown in the console:
Uncaught (in promise) TypeError: Cannot convert undefined or null to object
The API:
{
"message": "List trash and category order by time",
"data": [
{
"id": 1,
"trash_id": 1,
"category_id": 2,
"created_at": "2022-01-01T12:41:43.000000Z",
"updated_at": "2022-01-01T12:41:43.000000Z",
"garbage": {
"id": 1,
"name": "Buku",
"weight": 1,
"created_at": "2022-01-01T12:41:19.000000Z",
"updated_at": "2022-01-01T12:41:19.000000Z"
},
"categories": {
"id": 2,
"name": "Kertas",
"price": 1800
}
}]
}
Index.vue script:
<script>
import axios from "axios";
import { onMounted, ref } from "vue";
export default {
setup() {
// reactive state
let all_trash = ref([]);
onMounted(() => {
// get data from api endpoint
axios
.get("http://127.0.0.1:8000/api/trash")
.then((result) => {
all_trash.value = result.data;
})
.catch((err) => {
console.log(err.response);
});
});
return {
all_trash,
};
},
};
</script>
Index.vue HTML:
<div v-for="(trash, index) in all_trash.data" :key="index">
<div class="card rounded shadow mb-3">
<div class="card-body">
<div class="mx-3">
<h5 class="mb-4">{{ trash.garbage.name }}</h5>
<p>
{{ trash.categories.name }}
<span class="float-end">
<button class="btn" style="color: red">Hapus</button>
</span>
</p>
</div>
</div>
</div>
</div>
Just add a condition that not to render the loop until data is not set. The data from API end point is not available on the initial dom rendered and there is not data in all_trash.data hence the error. Just add a v-if on top of the div and hopefully it should work.
<div v-if=" all_trash.data">
<div v-for="(trash, index) in all_trash.data" :key="index">
<div class="card rounded shadow mb-3">
<div class="card-body">
<div class="mx-3">
<h5 class="mb-4">{{ trash.garbage.name }}</h5>
<p>
{{ trash.categories.name }}
<span class="float-end">
<button class="btn" style="color: red">Hapus</button>
</span>
</p>
</div>
</div>
</div>
</div>

How to store logged In user_id in vuejs

I am totally new in vew js and I am trying to store data in db and I am storing successfully when I entered the values manually but I want to store the user_id of logged in user.
Here is my vue
<form #submit.prevent>
<div class="form-group">
<label for="event_name">Name</label>
<input type="text" id="event_name" class="form-control" v-model="newEvent.event_name">
</div>
<div class="form-group">
<label for="user_id">Use Id</label>
<input type="text" id="user_id" class="form-control" v-model="newEvent.user_id">
</div>
<div class="col-md-6 mb-4" v-if="addingMode">
<button class="btn btn-sm btn-primary" #click="addNewEvent">Save Event</button>
</div>
</form>
export default {
components: {
Fullcalendar
},
data() {
return {
calendarPlugins: [dayGridPlugin, interactionPlugin],
events: "",
newEvent: {
event_name: "",
user_id: ""
},
addingMode: true,
indexToUpdate: ""
};
},
created() {
this.getEvents();
},
methods: {
addNewEvent() {
axios
.post("/fullcalendar/api/calendar", {
...this.newEvent
})
.then(data => {
this.getEvents(); // update our list of events
this.resetForm(); // clear newEvent properties (e.g. title and user_id)
})
.catch(err =>
console.log("Unable to add new event!", err.response.data)
);
},
Here, when I enter values in Name and User Id manually then it stores in db but in user id I want to get the logged in user_id.
I have tried something like this but it didn't work,
<input type="text" id="user_id" class="form-control" v-model="newEvent.{{ Auth::user()->id; }}">
Please help me out, Thanks in advance.
EventResource.php
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->event_name,
'user' => $this->user_id,
];
}
you can send data with your axios request like this:
axios.post('/url', {
user_id: {{ Auth::user()->id }}
}, {
headers: headers
})
and in your controller you can access it with:$request->user_id;

Post request by axios (VueJS) in laravel giving 500 error

I am trying to make a post request via axios but getting this error: app.js:285 POST http://127.0.0.1:8000/concerts/1/orders 500 (Internal Server Error)
The order is being processed though (I see it coming is Stripe and database). Another problem is that redirect is not happening as window.location =/orders/${response.data.confirmation_number}; I just stay on the same page.
Any ideas what could go wrong here?
<template>
<div>
<div class="row middle-xs">
<div class="col col-xs-6">
{{ csrf_token}}
<div class="form-group m-xs-b-4">
<label class="form-label">
Price
</label>
<span class='form-control-static '>
${{ priceInDollars }}
</span>
</div>
</div>
<div class="col col-xs-6">
<div class="form-group m-xs-b-4">
<label class="form-label">
Qty
</label>
<input type="number" v-model="quantity" class="form-control">
</div>
</div>
</div>
<div class="text-right">
<button class="btn btn-primary btn-block"
#click="openStripe"
:class="{ 'btn-loading': processing }"
:disabled="processing"
>
Buy Tickets
</button>
</div>
</div>
This is script part:
<script>
export default {
props: [
'price',
'concertTitle',
'concertId',
],
data() {
return {
quantity: 1,
stripeHandler: null,
processing: false,
}
},
computed: {
description() {
if (this.quantity > 1) {
return `${this.quantity} tickets to ${this.concertTitle}`
}
return `One ticket to ${this.concertTitle}`
},
totalPrice() {
return this.quantity * this.price
},
priceInDollars() {
return (this.price / 100).toFixed(2)
},
totalPriceInDollars() {
return (this.totalPrice / 100).toFixed(2)
},
},
methods: {
initStripe() {
const handler = StripeCheckout.configure({
key: App.stripePublicKey
})
window.addEventListener('popstate', () => {
handler.close()
})
return handler
},
openStripe(callback) {
this.stripeHandler.open({
name: 'TicketBeast',
description: this.description,
currency: "usd",
allowRememberMe: false,
panelLabel: 'Pay {{amount}}',
amount: this.totalPrice,
// image: '/img/checkout-icon.png',
token: this.purchaseTickets,
})
},
purchaseTickets(token) {
this.processing = true
axios.post(`/concerts/${this.concertId}/orders`, {
email: token.email,
ticket_quantity: this.quantity,
payment_token: token.id,
}).then(response => {
window.location =`/orders/${response.data.confirmation_number}`;
console.log('Charge succeeded.')
}).catch(response => {
this.processing = false
})
}
},
created() {
this.stripeHandler = this.initStripe()
}
}
You have to go and look under the Network tab if you are using Chrome browser, you can see the failed request response
The issue turns out to be Mailer. In .env file, along with Mailtrap credentials you must provide sender email and they don't tell you that :( This also somehow prevented the redirect. In case that helps someone.

"TypeError: Cannot read property 'title' of undefined" in form

An error is returned when I try to post the form.
The form is in a component, and the same structure is used in another component but does not generate any error.
I tried to find the mistake by myself but impossible to find the solution.
<template>
<div class="card" style="width: 18rem;margin:0 0 1rem 1rem;">
<div class="card-body">
<h4 class="mt-3 text-center" style="cursor:pointer;" #click="show=!show" >Add list</h4>
<form v-show="show" #submit.prevent="submitList">
<div class="form-group">
<label>Title</label>
<input type="text" class="form-control" :class="{'is-invalid':errors.title}" v-model="form.title"/>
<p class="text-danger" v-if="errors.title" v-text="errors.title[0]"></p>
</div>
<button type="submit" class="btn btn-lg btn-success mb-4">Submit</button>
</form>
</div>
</div>
</template>
<script>
export default {
data() {
return {
show : false,
form: {
title: '',
},
errors: {}
}
},
methods: {
submitList() {
axios.post('/list', this.form)
.then(({data}) => {
this.$emit('newList', data),
this.form.title = '',
this.show = false,
this.errors = {}
})
.catch(error => {
this.errors = error.response.data.errors
})
}
}
}
</script>
Error in render: "TypeError: Cannot read property 'title' of undefined"
Reference this at the start of the method submitList and then use the reference in the axios response.
let that = this;
then that.form.title;
submitList () {
let that = this;
axios.post('/list', this.form)
.then(({ data }) => {
that.$emit('newList', data),
that.form.title = '',
that.show = false,
that.errors = {}
})
.catch(error => {
that.errors = error.response.data.errors
})
}
There's not really enough information here to answer the question. Since it's a render issue my guess is that it's one of these lines:
<input type="text" class="form-control" :class="{'is-invalid':errors.title}" v-model="form.title"/>
<p class="text-danger" v-if="errors.title" v-text="errors.title[0]"></p>
The question is what you get from the backend in your catch method. You should probably log that value and check that it's formated the way you think it is.
A nice tool for debugging Vue is the browser extension, maybe it will help with clearing up the problem.
If this does not solve your problem you need to provide more info:
When does the error occur
What is the value of the data-properties when it occurs
Maybe a screenshot of a more thorough error-message

No error messages from 422 response on laravel form request from vue component

I'm trying to submit a form request using axios, have it validated, and return errors if the validation fails. The problem is, when I submit the form, no error messages are returned for me to show on the client side. Here's the HTTP request and vue component:
<div class="card">
<div class="card-header">
<h4>Information</h4>
</div>
<div class="card-body">
<p v-if='!isEditMode'><strong>Name:</strong> {{businessData.name}}</p>
<div class="form-group" v-if='isEditMode'>
<strong><label for="business-name">Name</label></strong>
<input class="form-control" name="business-name" v-model='businessData.name'>
</div>
<p v-if='!isEditMode'><strong>Description:</strong> {{businessData.description}}</p>
<div class="form-group" v-if='isEditMode'>
<strong><label for="business-description">Description</label></strong>
<textarea class="form-control normal" name="business-description"
placeholder="Enter your services, what you sell, and why your business is awesome"
v-model='businessData.description'></textarea>
</div>
</div>
</div>
<div class="card">
<h4 class="card-header">Address Information</h4>
<div class="card-body">
<p v-if="!isEditMode"><strong>Street Address: </strong> {{businessData.street}}</p>
<div class="form-group" v-if='isEditMode'>
<strong><label for="business-street">Street Address: </label></strong>
<input type="text" class="form-control" name="business-street" v-model='businessData.street' placeholder="1404 e. Local Food Ave">
</div>
<p v-if="!isEditMode"><strong>City: </strong> {{businessData.city}}</p>
<div class="form-group" v-if='isEditMode'>
<strong><label for="business-city">City: </label></strong>
<input class="form-control" type="text" name="business-city" v-model='businessData.city'>
</div>
<p v-if="!isEditMode"><strong>State: </strong> {{businessData.state}}</p>
<div class="form-group" v-if='isEditMode'>
<strong><label for="business-state">State: </label></strong>
<select class="form-control" name="business-state" id="state" v-model="businessData.state" >...</select>
</div>
<p v-if="!isEditMode"><strong>Zip: </strong> {{businessData.zip}}</p>
<div class="form-group" v-if='isEditMode'>
<strong><label for="business-zip">Zip: </label></strong>
<input class="form-control" type="text" maxlength="5" name="business-zip" v-model='businessData.zip'>
</div>
</div>
</div>
<div class="card">
<h4 class="card-header">Contact Information</h4>
<div class="card-body">
<p v-if="!isEditMode"><strong>Phone: </strong> {{businessData.phone}}</p>
<div class="form-group" v-if='isEditMode'>
<strong><label for="business-phone">Phone: </label></strong>
<input class="form-control" type="tel" name="business-phone" v-model='businessData.phone'>
</div>
<p v-if="!isEditMode"><strong>Email: </strong> {{businessData.email}}</p>
<div class="form-group" v-if='isEditMode'>
<strong><label for="business-Email">Email: </label></strong>
<input class="form-control" type="email" name="business-email" v-model='businessData.email'>
</div>
</div>
</div>
</div>
<script>
export default {
data () {
return {
isEditMode: false,
businessData: this.business,
userData: this.user,
errors: []
}
},
props: {
business: {},
user: {},
role: {}
},
//Todo - Institute client side validation that prevents submission of faulty data
methods: {
validateData(data) {
},
saveBusinessEdits () {
axios.put('/businesses/' + this.business.id , {updates: this.businessData})
.then(response => {
console.log(response.data)
// this.businessData = response.data;
this.isEditMode = false;
})
.catch (response => {
console.log(response.data)
this.isEditMode = false;
})
},
saveUserEdits () {
axios.put('/profile/' + this.user.id , {updates: this.userData})
.then(response => {
console.log(response.data)
this.userData = response.data;
this.isEditMode = false;
})
.catch (response => {
console.log(response)
this.isEditMode = false;
})
}
}
}
Route
Route::put('/businesses/{id}', 'BusinessesController#update');
BusinessController and update function
public function update(BusinessRequest $request, $id)
{
$business = Business::find($id)->update($request->updates);
$coordinates = GoogleMaps::geocodeAddress($business->street,$business->city,$business->state,$business->zip);
if ($coordinates['lat']) {
$business['latitude'] = $coordinates['lat'];
$business['longitude'] = $coordinates['lng'];
$business->save();
return response()->json($business,200);
} else {
return response()->json('invalid_address',406);
}
$business->save();
return response()->json($business,200);
}
and BusinessRequest class
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'business-name'=> 'required|string|max:255',
'business-description'=> 'required|string',
'business-phone' => 'nullable|phone|numeric',
'business-email' => 'nullable|email',
'business-street'=> 'required|string',
'business-city' => 'required|string',
'business-state' => 'required|string|max:2',
'business-zip' => 'required|min:5|max:5|numeric',
];
}
public function messages() {
return [
'business-zip.min:5' =>'your zip code must be a 5 characters long',
'business-email.email'=>'your email is invalid',
'business-phone.numeric'=>'your phone number is invalid',
];
}
}
I don't understand why, even if input valid data, it responds with a 422 response and absolutely no error messages. Since this is laravel 5.6, the 'web' middleware is automatic in all of the routes in the web.php file. So this isn't the problem. Could anyone help me normalize the validation behavior?
In Laravel a 422 status code means that the form validation has failed.
With axios, the objects that are passed to the then and catch methods are actually different. To see the response of the error you would actually need to have something like:
.catch (error => {
console.log(error.response)
this.isEditMode = false;
})
And then to get the errors (depending on your Laravel version) you would have something like:
console.log(error.response.data.errors)
Going forward it might be worth having a look at Spatie's form-backend-validation package
You can use Vue.js and axios to validate and display the errors. Have a route called /validate-data in a controller to validate the data.
app.js file:
import Vue from 'vue'
window.Vue = require('vue');
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
let token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
class Errors {
constructor() {
this.errors = {};
}
get(field) {
if (this.errors[field]) {
return this.errors[field][0];
}
}
record(errors) {
this.errors = errors;
}
clear(field) {
delete this.errors[field];
}
has(field) {
return this.errors.hasOwnProperty(field);
}
any() {
return Object.keys(this.errors).length > 0;
}
}
new Vue({
el: '#app',
data:{
errors: new Errors(),
model: {
business-name: '',
business-description: '',
business-phone: ''
},
},
methods: {
onComplete: function(){
axios.post('/validate-data', this.$data.model)
// .then(this.onSuccess)
.catch(error => this.errors.record(error.response.data.errors));
},
}
});
Make a route called /validate-data with a method in the controller, do a standard validate
$this->validate(request(), [
'business-name'=> 'required|string|max:255',
'business-description'=> 'required|string',
'business-phone' => 'nullable|phone|numeric',
'business-email' => 'nullable|email',
'business-street'=> 'required|string',
'business-city' => 'required|string',
'business-state' => 'required|string|max:2',
'business-zip' => 'required|min:5|max:5|numeric'
]
);
Then create your inputs in your view file, using v-model that corresponds to the vue.js data model fields. Underneath it, add a span with an error class (basic red error styling, for example) that only shows up if the errors exist. For example:
<input type="text" name="business-name" v-model="model.business-name" class="input">
<span class="error-text" v-if="errors.has('business-name')" v-text="errors.get('business-name')"></span>
Don't forget to include the app.js file in footer of your view file. Remember to include the tag, and run npm run watch to compile the vue code. This will allow you to validate all errors underneath their input fields.
Forgot to add, have a buttton that has #onclick="onComplete" to run the validate method.

Resources