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

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

Related

422 Unprocessable Entity Error. I tried upload Excel file to import data but it is not working

This is my code, i use vuejs and laravel. The function I am doing is both saving the Course and also importing the Excel file to get the data in the file. But when saving the Course is normal, but when it comes to running the validate excel file line, the error is not received. Even though I gave it a name and console.log came out. Can you help me fix it? Thank you so much.
Component - template tag
<form #submit.prevent="store()" #keydown="form.onKeydown($event)">
<div class="form-group">
<label class="form-label">Courses</label>
<select class="form-control" name="education_program_course" v-model="form.education_program_course">
<option value="" disabled selected="">Select option</option>
<option value="" disabled>-------</option>
<option v-for="course in courses" :key="course.course_code" :value="course.course_code">{{ course.course_name }}</option>
</select>
</div>
<div class="form-group">
<label class="form-label">Excel File</label>
<input type="file" class="form-control" id="file_data" name="file_data" ref="fileupload" #change="onFileChange">
</div>
<div class="card-footer text-right">
<button :disabled="form.busy" class="btn btn-success btn-lg mt-1" type="submit">Save</button>
</div>
</form>
Component - script tag
export default: {
data() {
return {
file_data: "",
form: new Form({
education_program_course
}),
},
methods: {
onFileChange(e) {
this.file_data = e.target.files[0];
},
store() {
this.form.busy = true;
let formData = new FormData();
formData.append('file_data', this.file_data);
this.form.post('../../api/admin/program/education', formData, {
headers: { 'content-type': 'multipart/form-data' }
})
.then(res => {
if(this.form.successful){
this.$snotify.success('Sucessful!');
this.form.clear();
this.form.reset();
}
})
.catch(err => {
this.$snotify.error(err.response.data.errors.file_data[0]);
});
},
}
}
}
Controller
$data = $request->validate([
'education_program_course' => ['required'],
'file_data' => ['required', 'file', 'mimes:xls,xlsx']
]);
$program = new EducationProgram();
$program->education_program_course = $data['education_program_course'];
$path = $request->file($data['file_data'])->getRealPath();
Excel::import(new ProgramDetailImport, $path);
You should append 'education_program_course' on your formdata.
formData.append('education_program_course', this.form.education_program_course);
I have solved this problem. Change change at script tag -> store()
from:
let formData = new FormData();
formData.append('file_data', this.file_data);
to:
if(document.getElementById("file_data").files[0]){
this.form.file_data = document.getElementById("file_data").files[0];
}
Adding file_date in form: new Form and remove formData in this.form.post.

3 errors on function from vue js

My errors:
app.js:44406 [Vue warn]: Property or method "__" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
found in ---> <ChatComponent> at resources/js/components/ChatComponent.vue
app.js:44406 [Vue warn]: Error in render: "TypeError: vm._ is not a function" found in
---> <ChatComponent> at resources/js/components/ChatComponent.vue
TypeError: vm._ is not a function.
<template>
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="card">
<div class="card-body minh overflow-auto"></div>
</div>
<div class="mt-3">
<div class="form-group">
<div class="input-group mb-3">
<input
type="text"
class="form-control"
v-bind:placeholder="placeholder"
aria-label="Recipient's username"
aria-describedby="button-addon2"
v-model="messageField"
/>
<div class="input-group-append">
<button class="btn btn-primary" type="button" id="button-addon2">{{__('auth.submit')}}</button>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
let messages = {};
export default {
data() {
return{
messages: {},
messageField: ""
}
},
props:[
'placeholder'
],
mounted() {
this.getMessagess();
},
methods: {
getMessagess() {
axios
.get("/messagefetch")
.then(response => {
this.messages = response.data;
})
.catch(function(error) {
console.log(error);
});
},
postMessage() {
axios
.post("/api/messagesend", {
api_token: this.user.api_token,
message: this.messageField
})
.then(response => {
this.message.push(response.data);
this.messageField = "";
})
.catch(function(error) {
console.log(error);
});
}
}
};
</script>
I get my messages from the database and my prop placeholder is also good but i dont see my component in the front-end. Also, I get 3 errors for functions made by vue.js itself, which get compiled and put in app.js. Im new at vue.js so im not sure what im doing wrong
You are mixing frontend and backend functions. The __ function is a laravel specific helper for localisation of text. But you cannot use a laravel php function inside Vue JavaScript. Therefore you get errors that the function is not found, etc.
You need to configure localisation separately for your frontend. Have a look at: https://kazupon.github.io/vue-i18n/

Toggle form in nested v-for loop in VueJS

I have a list of nested comments. Under each comment, I'd like to add a "reply" button that, when click, show a reply form.
For now, everytime I click a "reply" button, it shows the form. But the thing is, I'd like to show only one form on the whole page. So basically, when I click on "reply" it should close the other form alreay opened and open a new one under the right comment.
Edit :
So I was able to make some slight progress. Now I'm able to only have one active form opening on each level of depth in the nested loop. Obviously, what I'm trying to do now is to only have one at all.
What I did was emitting an event from the child component and handle everything in the parent component. The thing is, it would work great in a non-nested comment list but not so much in my case...
Here is the new code:
In the parentComponent, I have a handleSelected method as such:
handleSelected (id) {
if(this.selectedItem === id)
this.selectedItem = null;
else
this.selectedItem = id;
},
And my childComponent:
<template>
<div v-if="comment">
<div v-bind:style=" iAmSelected ? 'background: red;' : 'background: none;' ">
<p>{{ comment.author.name }}<br />{{ comment.created_at }}</p>
<p>{{ comment.content }}</p>
<button class="button" #click="toggle(comment.id)">Répondre</button>
<button class="button" #click="remove(comment.id)">Supprimer</button>
<div v-show="iAmSelected">
<form #submit.prevent="submit">
<div class="form-group">
<label for="comment">Votre réponse</label>
<textarea class="form-control" name="comment" id="comment" rows="5" v-model="fields.comment"></textarea>
<div v-if="errors && errors.comment" class="text-danger">{{ errors.comment[0] }}</div>
</div>
<button type="submit" class="btn btn-primary">Envoyer</button>
<div v-if="success" class="alert alert-success mt-3">
Votre réponse a bien été envoyée !
</div>
</form>
</div>
</div>
<div v-if="comment.hasReply">
<div style="margin-left: 30px;">
<comment v-for="comment in comments"
:key="comment.id"
:comment="comment" #remove-comment="remove"
:is-selected="selectedItem" #selected="handleSelected($event)">
</comment>
</div>
</div>
</div>
</template>
<script>
import comment from './CommentItem'
export default {
name: 'comment',
props: {
isSelected: Number,
comment: {
required: true,
type: Object,
}
},
data () {
return {
comments: null,
fields: {},
errors: {},
success: false,
loaded: true,
selectedItem: null,
}
},
computed: {
iAmSelected () {
return this.isSelected === this.comment.id;
}
},
methods: {
remove(id) {
this.$emit('remove-comment', id)
},
toggle(id) {
this.$emit('selected', id);
},
handleSelected(id) {
if(this.selectedItem === id)
this.selectedItem = null;
else
this.selectedItem = id;
},
},
mounted(){
if (this.comment.hasReply) {
axios.get('/comment/replies/' + this.comment.id)
.then(response => {
this.comments = response.data
})
}
}
}
</script>
Thanks in advance for your help!

How to empty input fields from a pop-up window after submitting - Vue - laravel?

My page exist of a table where I can add new rows. If you want to add a new row a pop-up window appear where the new values can be added.
This new data is then saved to the database after submitting. If I again want to add a new row the input fields, they should be cleared.
The method I use, is working but isn't very clear.
Note: My code shows only a part of the input fields, to make it more clear. My pop-up window actually contains 20 input fields.
I would like to clear them all at once instead of clearing them one by one (like I am doing now).
Because I am already doing this for defining the v-model, pushing the new data to the database directly on the page and via post axios request.
Is there a cleaner way to do this?
Thanks for any input you could give me.
This is my code:
html part
<div class="col-2 md-2">
<button class="btn btn-success btn-sx" #click="showModal('add')">Add New</button>
<b-modal :ref="'add'" hide-footer title="Add new" size="lg">
<div class="row" >
<div class="col-4">
<b-form-group label="Category">
<b-form-input type="text" v-model="newCategory"></b-form-input>
</b-form-group>
</div>
<div class="col-4">
<b-form-group label="Name">
<b-form-input type="text" v-model="newName" placeholder="cd4"></b-form-input>
</b-form-group>
</div>
<div class="col-4">
<b-form-group label="Amount">
<b-form-input type="number" v-model="newAmount" ></b-form-input>
</b-form-group>
</div>
</div>
<div class="row" >
<div class="col-8">
</div>
<div class="col-4">
<div class="mt-2">
<b-button #click="hideModal('add')">Close</b-button>
<b-button #click="storeAntibody(antibodies.item)" variant="success">Save New Antibody</b-button>
</div>
</div>
</div>
</b-modal>
</div>
js part
<script>
import { async } from 'q';
export default {
props: ['speciedata'],
data() {
return {
species: this.speciedata,
newCategory: '',
newName: '',
newAmount:'',
}
},
computed: {
},
mounted () {
},
methods: {
showModal: function() {
this.$refs["add"].show()
},
hideModal: function(id, expId) {
this.$refs['add'].hide()
},
addRow: function(){
this.species.push({
category: this.newCategory,
name: this.newName,
amount: this.newAmount,
})
},
storeSpecie: async function() {
axios.post('/specie/store', {
category: this.newCategory,
name: this.newName,
amount: this.newAmount,
})
.then(this.addRow())
// Clear input
.then(
this.newName = '',
this.newCategory = '',
this.newAmount = '',
)
.then(this.hideModal('add'))
},
}
}
</script>
in your data of vuejs app , you have to set one object for displaying modal data like modalData then to reset data you can create one function and set default value by checking type of value using loop through modalData object keys
var app = new Vue({
el: '#app',
data: {
message:"Hi there",
modalData:{
key1:"value1",
key2:"value2",
key3:"value3",
key4:5,
key5:true,
key6:"val6"
}
},
methods: {
resetModalData: function(){
let stringDefault="";
let numberDefault=0;
let booleanDefault=false;
Object.keys(this.modalData).forEach(key => {
if(typeof(this.modalData[key])==="number"){
this.modalData[key]=numberDefault;
}else if(typeof(this.modalData[key])==="boolean") {
this.modalData[key]=booleanDefault;
}else{
// default type string
this.modalData[key]=stringDefault;
}
});
}
}
})
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<div id="app">
{{modalData}}
<br/>
<button #click="resetModalData">Reset Modal Data</button>
</div>
update : in your case :
data:{
species: this.speciedata,
modalData:{
newCategory: '',
newName: '',
newAmount:''
}
},
and after storing data :
storeSpecie: async function() {
axios.post('/specie/store', {
category: this.newCategory,
name: this.newName,
amount: this.newAmount,
})
.then(()=>{
this.addRow();
this.resetModalData();
this.hideModal('add')
}
},
In native Javascript you get the reset() method.
Here is how it is used :
document.getElementById("myForm").reset();
It will clear every input in the form.

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