How to display records from Laravel via Vuetify v-data-table component - laravel

I have a project build in Laravel with Vue.js which work perfect statically, but I need convert it into dynamically to pull records from database table to v-data-table component.
I know Laravel and I know How these things works via Ajax/jQuery but I'm pretty new in Vue.js
Can someone explain to me how to display the results from the database in the v-data-table component.
Thanks.
Here is the Vue.js file:
<template>
<v-app>
<v-main>
<div>
<v-tab-item>
<v-card flat>
<v-card-text>
<v-card-title>
<v-spacer></v-spacer>
<v-text-field
v-model="search"
append-icon="mdi-magnify"
label="Search"
single-line
hide-details
></v-text-field>
</v-card-title>
<v-data-table
:headers="headers"
:items="items"
:items-per-page="5"
class=""
:search="search">
</v-data-table>
</v-card-text>
</v-card>
</v-tab-item>
</div>
</v-main>
</v-app>
</template>
<script>
export default {
data: () => ({
search: '',
items: [],
headers: [
{
text: '#',
align: 'start',
sortable: false,
value: 'id',
},
{ text: 'Name', value: 'name' },
{ text: 'Slug', value: 'slug' },
],
/*THIS IS A STATIC DATA*/
// items: [
// {
// id: 1,
// name: 'Test Name 1',
// slug: 'test-name-1',
// },
// {
// id: 2,
// name: 'Test Name 2',
// slug: 'test-name-2',
// },
// ],
/*THIS IS A STATIC DATA*/
}),
created () {
this.getItems();
},
methods: {
getItems() {
axios
.get('/test/vue')
.then((response) => {
this.items = response.data,
console.log(response.data)
})
.catch(error => console.log(error))
},
}
}
</script>
And Here is Blade file:
#extends('it-pages.layout.vuetify')
#section('content')
<div id="appContainer">
<software-template></software-template>
</div>
Output in the console is :
console.log
Response from axios is also Ok
response
My Controller :
public function showData()
{
$items = Category::select('id', 'name', 'slug')->where('order', 1)->get();
// dd($items);
return response()->json(['items' => $items]);
}
My route:
Route::get('test/vue', 'PagesController#showData');
console.log after changes axios lines
console-log

So there were multiple issues here:
The backend did you return a correct array
The frontend performed a post request instead of a get
The this context is not correct since you are using a function instead of arrow syntax
Make sure to look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions and read about how this changes how this is elevated.
In your case, you need to change the code on the then part of your axios call:
.then((response) => {
this.items = response.data
})

I must to say that I solve the problem.
Problem was been in axios response.
Instead this.items = response.data I change to this.items = response.data.items and it work perfectly.
methods: {
getItems() {
axios
.get('/test/vue')
.then((response) => {
this.items = response.data.items
console.log(response.data.items)
})
.catch(error => console.log(error))
},
}

Related

nuxt,js vue,js how to fetch data inside of table

i am new in vuetify and nuxt.js
i am getting data from database but i want to show that in vuetify table.
Laravel API Controller
public function businesslist() {
$businesslist = Business::paginate(2)->toJson(JSON_PRETTY_PRINT);
return response($businesslist);
}
}
MY Laravel API
Route::get('/businesslist', 'BusinessController#userlist')->name('businesslist');
MY Nuxt.js vue page
<template>
<v-card>
<v-card-title>
Nutrition
<v-spacer></v-spacer>
<v-text-field
v-model="search"
append-icon="mdi-magnify"
label="Search"
single-line
hide-details
></v-text-field>
</v-card-title>
<v-data-table
:headers="headers"
:items="businessuser"
:search="search"
></v-data-table>
</v-card>
</template>
<script>
export default {
data() {
return {
search: '',
headers: [{
text: 'Name',
value: 'name'
},
{
text: 'Mobile ',
value: 'mobile_number'
},
{
text: 'Location ',
value: 'location'
},
{
text: 'Join Date ',
value: 'registration_date'
},
{
text: 'Renewal Date ',
value: 'registration_renewal_date'
},
],
businessuser: [
],
}
},async asyncData({$axios}) { let {data} = await $axios.$get('/businesslist')
return {
businesslist: data
} },
}
}
</script>
You should use created event, in this event, call your businesslist API and in the response, you should assign received data to your businessuser vue js variable.
Let see here one example.
created () {
this.initialize();
},
methods: {
initialize () {
this.businessuser = businesslistApiCalling();
}
}
businesslistApiCalling(); is just an example you should call here the API method to receive Json data from the Server.

How to append the axios result to vuejs datatables?

I am new to vuejs. I have a laravel+vue project in which I had used vuejs datatables for displaying all the users. I am stuck on why the data is not appending to the datatable :data property and I also tried to display data in <div v-for="user in users">{{ user.name }}</div> tag with for loop then it is displaying but when I used for loop in datatable then loop doesn't stops and also there is no error in the console. Please tell me the solution and thanks in advance. Here is my code.
UserController.php
public function index()
{
return response()->json(['users' => User::all()], 200);
}
UserComponent.vue
<template>
<datatable :columns="columns" :data="users"></datatable>
</template>
<script>
export default()
{
data()
{
return {
columns: [
{label: 'id', field: 'id'},
{label: 'Name', field: 'name'},
{label: 'Email', field: 'email'}
],
users: []
};
},
mounted()
{
this.getUsers();
},
methods:
{
getUsers()
{
axios.get('api/user')
.then(res => this.users = res.data.users)
.catch(err => console.log(err))
},
}
}
</script>

Return errors in server side validation with Laravel and Vue

I'm trying to return the errors in server side validation so the user can know which error they have, but I don't know how to return something that it is understandable for a normal person.
Here's my front-end
<v-form>
<v-row>
<v-col cols="12" sm="6" md="6">
<v-text-field label="Serial Number" v-model="plane.serial_number" color="black" counter="30"></v-text-field>
</v-col>
</v-row>
<v-btn color="yellow" class="black-text" #click="add()">Submit</v-btn>
</v-form>
<script>
import Swal from 'sweetalert2'
export default {
data() {
return {
errors: [],
plane: {
serial_number: '',
},
}
},
methods: {
add() {
const params = {
serial_number: this.plane.serial_number,
};
axios.post(`/planes`, params)
.then(res => {
Swal.fire({
title: 'Success!',
html: 'Plane created successfully!',
icon: 'success',
confirmButtonText: 'OK',
})
}).catch(e => {
this.errors = e;
console.log(this.errors);
Swal.fire({
title: 'Error!',
icon: 'error',
})
})
},
}
}
</script>
Back-end
public function store(Request $request)
{
$this->validate($request, [
'serial_number' => ['required','string', 'unique:airplanes']
]);
$airplane = new Airplane();
$airplane->serial_number = $request->serial_number;
$airplane->save();
}
The console.log isn't returning anything at all.
In this.errors if you output this.errors.message you should see a friendly message. Hope that helps! ... You can also dig into the this.errors.response object which has things like the headers and status.

Auto fill input field after Select dropdown list [ Laravel, Vuejs ]

I want to create something that search in Product table and i select in dropdown its will display data in order table like pic below?
how can i archieve that? Anyone give me any hint?
thanks in advances...
In my Vuetify
i used vue-select package
<v-col md="6" cols="12">
<label class="font-weight-bold">Select Product</label>
<v-select v-model="search" label="name" :options="purchases"></v-select>
</v-col>
In my script file
<script>
export default {
created() {
this.fetchData()
},
data() {
return {
form: {},
search: '',
items: [],
purchase_status: ['Received', 'Partial', 'Pending', 'Ordered'],
}
},
methods: {
fetchData() {
this.$axios.$get(`api/product`)
.then(res => {
this.items = res.data;
console.log(this.items)
})
.catch(err => {
console.log(err)
})
},
uploadFile(event) {
const url = 'http://127.0.0.1:3000/product/add_adjustment';
let data = new FormData();
data.append('file', event.target.files[0]);
let config = {
header: {
'content-Type' : 'image/*, application/pdf'
}
}
this.$axios.$post(url,data,config)
.then(res => {
console.log(res);
})
}
}
}
</script>
When you select a product in the dropdown, you'll get product_id. Use this product_id and call API to get data for the orders table.

Table Updates and AJAX Calls

I'm fairly new to Vue so I'm not sure whether being stupid or not.
I have a table that needs to be updated at a regular interval, so far I've used AJAX to make a call to an API and return the data and that all works great. I'm able to display all my data as required, the issue I'm facing, and this is where my knowledge gets fuzzy, is that on each AJAX call my entire table appears to be getting re-rendered, I thought, or rather hoped, that Vue would only "replace" the data that has changed not the whole table.
Is such a thing possible or am I asking too much?
I've included my code below incase I'm doing something wrong.
App.vue
<template lang="pug">
.user-agent-overview
.container
av-table(:columns="columns" :agentData="agentData")
</template>
<script>
import axios from 'axios';
import avTable from './Table';
export default {
data() {
return {
agentData: null,
columns: [
'Agent Name',
'Status',
'First Log in',
'Last Log out',
'Total On duty',
'Total Inbound',
'Total Outbound',
'Average Talk time',
'Total Talk time',
],
};
},
created() {
this.fetchAgentData();
},
methods: {
fetchAgentData() {
this.error = null;
this.agentData = null;
this.loading = true;
axios
.get('/api/v1/ajax-dashboard-aircall/agents')
.then(response => {
this.agentData = response.data.user_agents;
})
.catch(error => {
});
},
},
components: {
avTable,
},
mounted() {
// this.$nextTick(() => {
// setInterval(function() {
// this.fetchAgentData();
// }.bind(this), 5000);
// });
},
};
</script>
Table.vue
<template lang="pug">
table.table
thead
tr
th(v-for="column in columns") {{ column }}
tbody
tr(v-for="(data, dIndex) in agentData" :key="dIndex")
td(v-for="(item, iIndex) in data" :key="`${iIndex}-${iIndex}`") {{ item }}
</template>
<script>
import axios from 'axios';
export default {
props: ['columns', 'agentData'],
};
</script>
Thanks David

Resources