Retrieve data using axios vue.js - laravel

I retrieve data using axios in methods created () like this:
data() {
return {
filterBox: false,
color: [],
sortBy: null,
productType: [],
products: null,
productcolors: null,
categories: null,
active_el: 0,
isActive: false,
categories: null,
inputSearch: '',
}
},
created() {
axios.get('/admin/product_index_vue').then(response => {
this.products = response.data.products.data;
this.productcolors = response.data.productcolors;
this.categories = response.data.categories;
console.log(this.products.length);
}).catch((error) => {
alert("ERROR !!");
});
},
when checking using console.log the data is there :
Vue DevTools :
but when trying to check the mounted () function I get empty data
what is the cause of this problem?
what I really want is to create a filter, but when using this function the data will not appear :
computed: {
filteredProduct: function () {
if (this.products.length > 0) {
return this.products.filter((item) => {
return (this.inputSearch.length === 0 || item.name.includes(this.inputSearch));
});
}
}
},
HTML CODE :
<tr v-for="product in filteredProduct">
<td style="width:20px;">{{product.id}}</td>
<td class="table-img-product">
<img class="img-fluid" alt="IMG">
</td>
<td> {{ product.name }}</td>
<td style="display:none">{{product.product_code}}</td>
<td>{{ product.base_color }}</td>
<td>{{ product.category }}</td>
<td>{{ product.price }}</td>
<td>{{ product.stock }}</td>
<td>{{ product.status }}</td>
<td>
<button type="button" name="button" v-on:click="deleteProduct(product.id,product.product_color_id)">
<i class="fas fa-trash"></i>
</button>
</td>
</tr>
RESULT
app.js:36719 [Vue warn]: Error in render: "TypeError: Cannot read
property 'length' of null"
found in
---> at resources\assets\js\components\products\Product_index.vue
what causes this function to not work and no detected product data?

This is because the computed property will potentially be calculated before the response has been returned.
If your data properties are going to be an array then I would suggest defining them as an array from the beginning. In the data object change the properties to something like e.g.
products: [],
productcolors: [],
Alternatively, you can add an additional check to your computed property method:
filteredProduct: function () {
if (!this.products) {
return [];
}
return this.products.filter((item) => {
return (this.inputSearch.length === 0 || item.name.includes(this.inputSearch));
});
}

this is axios response ont wording
mounted: {
let self = this
axios.get('/admin/product_index_vue').then(response=>{
self.products=response.data.products.data;
self.productcolors =response.data.productcolors;
self.categories=response.data.categories;
console.log(self.products.length);
}).catch((error)=>{
alert("ERROR !!");
});
},

Related

how to delete data using vue js in laravel

i want to create a delete function with vue js in my laravel app.
here what i try
my .vue code
<tr v-for="(artist, index) in artists.data">
<td>{{ artist.artist_name }}</td>
<td>{{ artist.gender }}</td>
<td>{{ artist.created_at }}</td>
<td>{{ artist.updated_at }}</td>
<td>Edit | Delete</td>
my variable
data() {
return {
term:'',
disabled: 0,
artists: [],
results: [],
loading: false,
noResults: false,
SearchDiv: false,
IndexDiv: true
}
},
my delete method
deleteUser(id, index) {
axios.delete('/api/artist/'+id)
.then(resp => {
this.artists.splice(index, 1);
})
.catch(error => {
console.log(error);
})
}
error i get
TypeError: _this4.artists.splice is not a function
code above can delete data from database but not remove data from array result.
You are splicing data to its mother array.
Try this.
this.artists.data.splice(index, 1);

Can't get data in laravel vue

I try to show detail of my posts by slugs but data won't render. i just get my navbar and white page,
Code
controller
public function single($slug)
{
$post = Post::where('slug', $slug)->first();
return response()->json([
"post" => $post
], 200);
}
single.vue where i show my single post data
<template>
<div class="post-view" v-if="post">
<div class="user-img">
<img src="...." alt="">
</div>
<div class="post-info">
<table class="table">
<tr>
<th>ID</th>
<td>{{ post.id }}</td>
</tr>
<tr>
<th>Title</th>
<td>{{ post.title }}</td>
</tr>
<tr>
<th>Body</th>
<td>{{ post.body }}</td>
</tr>
</table>
<router-link to="/blog">Back to all post</router-link>
</div>
</div>
</template>
<script>
export default {
created() {
if (this.posts.length) {
this.project = this.posts.find((post) => post.slug == this.$route.params.slug);
} else {
axios.get(`/api/posts/${this.$route.params.slug}`)
.then((response) => {
this.post = response.data.post
});
}
},
data() {
return {
post: null
};
},
computed: {
currentUser() {
return this.$store.getters.currentUser;
},
posts() {
return this.$store.getters.posts;
}
}
}
</script>
vuex store.js
state: {
posts: []
},
getters: {
posts(state) {
return state.posts;
}
},
mutations: {
updatePosts(state, payload) {
state.posts = payload;
}
},
actions: {
getPosts(context) {
axios.get('/api/posts')
.then((response) => {
context.commit('updatePosts', response.data.posts);
})
}
}
Question
Why I can't get my post data? is there any mistake in my code?
................................................................................................................................................................................
You're calling /api/posts/${this.$route.params.slug}, which (by REST convention) returns ONE post object.
When setting your post (this.post = response.data.post) you should use response.data (without .post)

Return image with function show on *ngFor Angular 4

I have a function in component.ts as follow:
getImage(name) {
this._productService.getImage(name).subscribe((response) => {
// ??? my problem is here
});
}
and it's called here
<tr *ngFor="let i of data">
<td>{{ i.id }}</td>
<td><img [src]="getImage(i.image)" alt=""></td>
<td>{{ i.name }}</td>
<td>{{ i.price }}</td>
</tr>
So, how to my function return image?
P/S: my service get image from API ensure proper operation.
Thank for your help!
In your onInit use the below code,
this._productService.index().subscribe((data) => {
this.data = data;
console.log(data);
},
(error) => {
console.log(error);
},
() => {
this.data.forEach((element: IProduct) => {
element.image = element.image === null ? '' : this._productService.getImage((element.image));
});
});
As worked in teamviwer

Pushing ajax data to vue component

Having the following vue component
<employee-times :employees="{{$employees}}" :supplies="{{$supplies}}" :commits="{{$commits}}" :times="{{$times}}"></employee-times>
where I render the passed props
<template>
<div>
<select class="form-control input" v-model="currentYear" #change="filter()">
<option v-for="option in yearsOptions" v-bind:value="option">
{{ option }}
</option>
</select>
<tr v-for="employee,key in _employees" v-if="commits[key]">
<td>{{ key }}</td>
<td>{{ employee[0].first_name }}</td>
<td>{{ employee[0].last_name }}</td>
<td>{{ employee[0].nick }}</td>
<td>{{ employee[0].role }}</td>
<td>{{ employee[0].skill }}</td>
<td v-for="n in 12">
<div v-if="_commits[key][n]">{{ _commits[key][n].hours }}</div>
<div v-else> </div>
</td>
</tr>
</div>
</template>
than I try to filter the ajax data on change but the data will not update
here is the script what I'm trying, but from method function I'm not able to push the new data to the template
<script>
export default {
name: 'employee-times',
props: ['supplies', 'times', 'commits', 'employees'],
components: {
},
created() {
axios.get('/api/v1/roles', {
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
}).then(response => {
th
is.roles = response.data
}).catch(error => {
})
this._times = this.times;
this._commits = this.commits;
this._supplies = this.supplies;
this._employees = this.employees;
},
data() {
return {
count: 0,
yearsOptions: [],
_employees: {},
_supplies: {},
_times: {},
_commits: [],
currentYear: null,
currentStatus: 1,
currentPosition: 0,
statusOptions: [
{'id': '1',
'text': 'Active'
}, {'id': '0',
'text': 'Inactive'
}],
currentSkillset: 'all',
skillsetOptions: [
{'id': 'all',
'text': 'All'
}, {'l1': 'l1',
'text': 'L1'
}, {'l1': 'l2',
'text': 'L2'
}, {'l1': 'l3',
'text': 'L3'
}, {'l1': 'l4',
'text': 'L4'
}, {'l1': 'l5',
'text': 'L5'
}],
status: {},
roles: {},
skillsets: {}
};
},
mounted() {
this.currentYear = moment().format('Y')
var from = moment().subtract('4', 'years').format('Y')
var to = moment().add('2', 'years').format('Y')
while (from <= to) {
this.yearsOptions.push(from);
from++;
}
},
watch: {
'_employees': function (val, oldVal) {
console.log('new: %s, old: %s', val, oldVal)
}
},
methods: {
commit() {
},
clear() {
},
months() {
return moment.monthsShort()
},
filter() {
var data = {
year: this.currentYear,
status: this.currentStatus,
position: this.currentPosition,
//skill: currentSkillset
}
axios.post('/api/v1/supply/track-times', data, {
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
}).then(response => {
this._employees = {}
this.$set(this, '_employees', JSON.parse(response.data.employees))
this.$set(this,'_times', JSON.parse(response.data.times))
this.$set(this,'_supplies', JSON.parse(response.data.supplies))
this.$set(this, '_commits', JSON.parse(response.data.commits))
}).catch(error => {
})
}
},
};
</script>
What i missed in this case?
There's a problem with v-for and tables (ref 'v-for with 2 every time') that requires a template wrapper.
See example CodePen.
<div id='app'>
<table>
<template v-for="(employee, key) in employees">
<tr>
<td>{{ employee.first_name }}</td>
<td>{{ employee.last_name }}</td>
</tr>
</template>
<table>
</div>
It also appears that you do need to remove the underscores (try changing employee to _employee in the codepen).
Remove the "_" prefix from your data properties, then it should work. Vue uses underscores for internal stuff, so best avoid using it (see https://v2.vuejs.org/v2/api/#data)

Cannot access id being passed in vue.js and laravel

I am having hard time inserting the values which is the id that is being passed from the form into the controller of my enrollment system. To achieve this I make use of vue.js and vue-resource library. In my all.js file I am gettting the correct id value when I console.log the id being passed. However, when passing it to the route address of my application I am getting 500 error. Also, upon debugging I' m getting this error SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'section_subject_id' cannot be null (SQL: insert into reservations. How can I solve this?
ReservationController.php
class ReservationController extends Controller
{
public function create($id)
{
$subjects = Subject::with('sections')->get();
return view('reservation.form',compact('subjects'));
}
public function store(Request $request)
{
$subject = new Reservation();
$subject->section_subject_id = $request->input('id');
$subject->student_id = 1;
$subject->save();
}
}
all.js
Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('value');
new Vue({
el: '#app-layout',
data: {
subject: {
id : ''
},
subjects: []
},
ready: function(){
},
methods:{
addSubject: function(id){
this.subject = id;
this.$http({url: 'http://localhost:8000/reservation', id, method: 'POST'}).then(function(response){
}, function (response){
console.log('error');
});
}
}
});
form.blade.php
<body>
#foreach($subjects as $subject)
#foreach($subject->sections as $section)
<tr>
<td>{{ $section->section_code }}</td>
<td>{{ $subject->subject_code }}</td>
<td>{{ $subject->subject_description }}</td>
<td>{{ $section->pivot->schedule }}</td>
<td>{{ $subject->units }}</td>
<td>{{ $section->pivot->room_no }}</td>
<td>
<button
v-on:click="addSubject( {{ $section->pivot->id }} )"
class="btn btn-xs btn-primary">Add
</button>
<button class="btn btn-xs btn-info">Edit</button>
</td>
</tr>
#endforeach
#endforeach
</body>
Try formatting the data being sent like this: {id: this.id}
So your Vue addSubject Method looks like this:
addSubject: function(id){
this.subject = id;
this.$http({url: 'http://localhost:8000/reservation', {id: this.id}, method: 'POST'}).then(function(response){
}, function (response){
console.log('error');
});
}

Resources