Vuejs + Laravel: How To Count Records - laravel

Code for vue component:
data() {
return {
patrons : {},
}
},
methods: {
loadPatron(){
axios.get("api/patron")
.then(({data}) => (this.patrons= data.data));
//Count records
console.log(this.patrons.length); //This line of code does not seem to work.
},
}
How do we count the records and display them in the console.log?

You have to place console.log either inside axios get function after assignment
axios.get("api/patron")
.then(({data}) => {
this.patrons = data.data
console.log(this.patrons);
});
or create watcher for patrons property and console.log there
watch: {
patrons: {
handler: function() {
console.log(this.patrons)
},
deep: true
}
}

Related

vue.js how to call multiple url data in single axios

i am trying get multiple url data in single axios. i already added single url but i want to add another url.
i tired this but it giving null object error
{{ BusinessCount }}
{{ UserCount }}
import axios from "axios";
export default {
data() {
return {
businesslists: [],
Userslist: [],
};
},
async asyncData({ $axios }) {
let { datas } = await $axios.$get("/Userslist");
return {
Userslist: datas,
};
},
computed: {
UserCount() {
return Object.keys(this.Userslist).length;
},
},
async asyncData({ $axios }) {
let { data } = await $axios.$get("/Businessregisterlist");
return {
businesslists: data,
};
},
computed: {
BusinessCount() {
return Object.keys(this.businesslists).length;
},
},
};
i want to show like this
<p>{{ BusinessCount }}</p>
<p>{{ UserCount }}</p>
1st url
/Businessregisterlist
2nd url
/Userlist
my code
<template>
<p>{{ BusinessCount }}</p>
</template>
<script>
import axios from "axios";
export default {
data() {
return {
BusinessCounts: [],
};
},
async asyncData({ $axios }) {
let { datad } = await $axios.$get("/Businessregisterlist");
return {
BusinessCounts: datad,
};
},
computed: {
BusinessCount() {
return Object.keys(this.BusinessCounts).length;
},
},
};
</script>
In your tried code you define the asyncData function 2 times. That's incorrect. But you can make 2 calls to the server in a single asyncData function.
Try:
async asyncData({ $axios }) {
let { datad } = await $axios.$get("/Businessregisterlist");
let { dataUsers } = await $axios.$get("/Userslist");
return {
Businesslist: datad,
Userslist: dataUsers
};
},
computed: {
BusinessCount() {
return Object.keys(this.Businesslist).length;
},
UserCount() {
return Object.keys(this.Userslist).length;
},
},
Make sure you correctly define the Businesslist and Userslist in the data section.

Laravel and Vue Pagination Fail

When I press the page 2 on pagination component, page=2 data comes to application and data never shows up on screen and pagination goes to 1 and everything is going to start point. I use bootstrap-vue for ui component library.
pagination component image:
Vue data variables:
isBusy: false,
output: {
message: "",
status: false
},
currentPage: 1,
tableData:{},
laravel api routes
Route::prefix('/pcustomers')->group( function() {
Route::post('/load', 'App\Http\Controllers\EmailListController#postPCustomer');
Route::middleware('auth:api')->post('/post', 'App\Http\Controllers\EmailListController#postPCustomer')->middleware(['web']);
Route::middleware('auth:api')->get('/all', 'App\Http\Controllers\EmailListController#allPCustomers')->middleware(['web']);
Route::middleware('auth:api')->get('/pcdata', 'App\Http\Controllers\EmailListController#pcData')->middleware(['web']);
Route::middleware('auth:api')->get('/delete', 'App\Http\Controllers\EmailListController#deletePCustomer')->middleware(['web']);
});
EmailListController function
public function pcData()
{
$pcData = DB::table('email_list')
->join('users', 'users.id', '=', 'email_list.workerId')
->select('email_list.*', 'users.username')
->paginate(100);
return response()->json($pcData);
}
Pagination component:
<b-pagination
v-model="currentPage"
:total-rows="tableData.total"
:per-page="tableData.to"
#input="getNewPageData()"
first-number
last-number
>
</b-pagination>
Here the axios post method for getting the data
getNewPageData(){
let list = this;
list.isBusy = true;
const page = list.currentPage;
axios.get("api/v1/pcustomers/pcdata?page="+page)
.then(function (response) {
list.tableData = response.data;
list.isBusy = false;
})
.catch(function (error) {
list.output = error;
});
},
It works at here for page 1
created(){
this.getNewPageData(this.currentPage);
}
Data Response for page 1:
{
"current_page":1,
"data":[
"..."
],
"first_page_url":"http:\/\/127.0.0.1:8000\/api\/v1\/pcustomers\/pcdata?page=1",
"from":1,
"last_page":4,
"last_page_url":"http:\/\/127.0.0.1:8000\/api\/v1\/pcustomers\/pcdata?page=4",
"links":[
{
"url":null,
"label":"Previous",
"active":false
},
{
"url":"http:\/\/127.0.0.1:8000\/api\/v1\/pcustomers\/pcdata?page=1",
"label":1,
"active":true
},
{
"url":"http:\/\/127.0.0.1:8000\/api\/v1\/pcustomers\/pcdata?page=2",
"label":2,
"active":false
},
{
"url":"http:\/\/127.0.0.1:8000\/api\/v1\/pcustomers\/pcdata?page=3",
"label":3,
"active":false
},
{
"url":"http:\/\/127.0.0.1:8000\/api\/v1\/pcustomers\/pcdata?page=4",
"label":4,
"active":false
},
{
"url":"http:\/\/127.0.0.1:8000\/api\/v1\/pcustomers\/pcdata?page=2",
"label":"Next",
"active":false
}
],
"next_page_url":"http:\/\/127.0.0.1:8000\/api\/v1\/pcustomers\/pcdata?page=2",
"path":"http:\/\/127.0.0.1:8000\/api\/v1\/pcustomers\/pcdata",
"per_page":100,
"prev_page_url":null,
"to":100,
"total":366
}
I did some changes on b-table and axios and it works now.
<b-table
id="pcustomers-table"
ref="pcustomers-table"
:busy="isBusy"
:items="tableData"
:fields="fields"
:per-page="resourceData.per_page"
:sort-by.sync="sortBy"
:sort-desc.sync="sortDesc"
small
striped
hover
>
I removed :current-page="currentPage" here.
getPCustomersResourceData(){
let list = this;
list.isBusy = true;
const page = list.currentPage;
axios.get("api/v1/pcustomers/pcdata?page="+page)
.then(function (response) {
list.resourceData = response.data;
list.tableData = list.resourceData.data;
list.isBusy = false;
})
.catch(function (error) {
list.output = error;
});
},
I get the whole data and separate here like:
resourceData: {},
tableData:[],
Thanks to github.com/gilbitron and Kamlesh Paul.

Nuxt dynamic route population using graphQL

In nuxtconfig.js you can use
generate: { routes() {} }
to return all the dynamic routes for your app.
All the examples use axios ie:
import axios from 'axios'
export default {
generate: {
routes: function () {
return axios.get('https://my-api/users')
.then((res) => {
return res.data.map((user) => {
return {
route: '/users/' + user.id,
payload: user
}
})
})
}
}
}
How can i do this with graphQL / apollo?
I have tried this and some other combinations...
let v
apollo: {
posts: {
query: gql`
query posts {
posts {
title
}
}
`,
result({ data, loading, networkStatus }) {
v = data
}
}
},
generate: {
subFolders: true,
routes: function() {
return {
route: '/posts/' + v.title,
payload: v
}
}
},
The error is that i dont think apollo is able to be used in nuxtconfig?
This also doesnt work
generate: {
routes: function() {
apollo: {
posts: {
query:`query posts {
posts {
title
}
}
`,
result({ data, loading, networkStatus }) {
return {
route: '/posts/' + data.title,
payload: data
}
}
}
},
}
},

Error TypeError: Cannot read property 'dispatch' of undefined at app.js:12012

Hi I've been trying to learn vuejs and vuex while trying to get response from an api call with vuex concept I got the following error.Please help.
This error occurred
Error TypeError: Cannot read property 'dispatch' of undefined
at app.js:12012
loginAction.js
export const getUsersList = function (store) {
let url = '/Apis/allUsers';
Vue.http.get(url).then((response) => {
store.dispatch('GET_USER_RES', response.data);
if (response.status == 200) {
}
}).catch((response) => {
console.log('Error', response)
})
}
loginStore.js
const state = {
userResponse: []
}
const mutations = {
GET_USER_RES (state, userResponse) {
state.userResponse = userResponse;
}
}
export default {
state, mutations
}
login.vue
import {getUsersList} from './loginAction';
export default {
created () {
try{
getUsersList();
}catch(e){
console.log(e);
}
},
vuex: {
getters: {
getUsersList: state => state.userResponse
},
actions: {
getUsersList
}
}
}
</ script>
If you call the actions manually (like in your try/catch) they'll not get the store context as the first argument. You could use getUsersList(this.store) I think, but instead I would use dispatch to reach all your actions. (I edited just a little bit to get a minimal running example, but I think you get the point!)
new Vue({
render: h => h(App),
created() {
this.$store.dispatch('getUsersList');
},
store: new Vuex.Store({
getters: {
getUsersList: state => state.userResponse
},
actions: {
getUsersList
}
})
}).$mount("#app");
Also, use commit to reach the mutations instead of dispatch. ie:
export const getUsersList = function ({commit}) {
let url = '/Apis/allUsers';
Vue.http.get(url).then((response) => {
commit('GET_USER_RES', response.data); // because GET_USER_RES is a mutation
...

Can't invoke the component's method

Using an EventBus on my Laravel-Vuejs project. I'm emitting an items-updated event from ItemCreate component after the successful Item creation. On the same page I'm using ItemList component which shows a list of created Items
Here is the codes:
app.js file
require('./bootstrap');
window.Vue = require('vue');
window.EventBus = new Vue();
Vue.component('item-list',
require('./components/entities/item/ItemList'));
Vue.component('item-create',
require('./components/entities/item/ItemCreate'));
const app = new Vue({
el: '#app'
});
ItemCreate.vue Component
export default {
data: function () {
return {
itemName: ''
}
},
methods: {sendItemData: function () {
axios.post('/dashboard/item', {
name: this.itemName
})
.then(response => {
if (response.status === 201) {
toastr.success('Item created successfully!', {timeout: 2000});
EventBus.$emit('items-updated');
}
})
.catch(error => {
toastr.error(error, 'Ooops! Something went wrong!');
})
}
}
}
ItemList.vue Component
export default {
data: function () {
return {
items: [],
}
},
methods: {
getItems: function () {
axios.get('/dashboard/items')
.then(response => {
this.items = response.data;
})
.catch(error => {
toastr.error(error, 'Ooops! Something went wrong!');
})
}
},
mounted() {
this.getItems();
EventBus.$on('items-updated', function () {
this.getItems();
});
}
}
It was a general JS mistake. Working code:
on ItemList.vue Component
export default {
data: function () {
return {
items: [],
}
},
methods: {
getItems: function () {
axios.get('/dashboard/items')
.then(response => {
this.items = response.data;
})
.catch(error => {
toastr.error(error, 'Ooops! Something went wrong!');
})
}
},
mounted() {
this.getItems();
let vm = this;
EventBus.$on('items-updated', function () {
vm.getItems();
});
}
}

Resources