how to delete data using vue js in laravel - 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);

Related

Datatable display problem using vue-axios and laravel

Im using jQuery datatables for displaying my data in my users component in Vue.js, but when I run my code it displays the data but it has some text that says "No data found". Can someone help me with this? I really don't have any idea because I'm new in this Frontend tools.
Users.vue:
<template>
<table id="table" class="table table-striped table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Type</th>
<th>Created</th>
</tr>
</thead>
<tbody>
<tr v-for="user in users" :key="user.id">
<td>{{ user.id }}</td>
<td>{{ user.name }}</td>
<td>{{ user.email }}</td>
<td>{{ user.type }}</td>
<td>{{ user.created_at }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
users: [],
form: new Form({
id: "",
name: "",
email: "",
password: "",
type: ""
})
};
},
methods: {
loadUsers() {
axios.get("api/user").then(({ data }) => (this.users = data));
}
},
created() {
console.log("Component mounted.");
this.loadUsers();
}
};
$(document).ready(function() {
$("#table").DataTable({});
});
</script>
Probably, you should init your widget DataTable after receiving data from api, more precisely in then method.
axios.get("api/user").then(({ data }) => {
this.users = data;
this.$nextTick(() => {
$("#table").DataTable({});
});
});
Explanation about Vue.$nextTick:
Defer the callback to be executed after the next DOM update cycle. Use
it immediately after you’ve changed some data to wait for the DOM
update. This is the same as the global Vue.nextTick, except that the
callback’s this context is automatically bound to the instance calling
this method.
axios.get("api/user").then(({ data }) => {
this.users = data;
$(function() {
$("#table").DataTable({});
});
});

Loop array with vue in laravel

can anyone help me on the following problem please.
I'd like to run a simple array via a loop within vue in laravel to give all the array values out in a table. This is my code I adjusted from a tutorial I found in the internet: enter code here
<template>
<div>
<h1>Coffeetypes</h1>
<table class="table table-hover">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr v-for="cctyp in cctypes" v-bind:key="cctyp.id">
<td>{{ cctyp.id }}</td>
<td>{{ cctyp.name }}</td>
<td>{{ cctyp.description }}</td>
<td><button class="btn btn-danger">Delete</button></td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
data() {
return {
cctypes: [],
cctyp: {
id: '',
name: '',
description: '',
created_by: '',
updated_by: ''
},
id: '',
pagination: {},
edit: false
};
},
created() {
this.fetchCCTypes();
},
methods: {
fetchCCTypes(){
fetch('api/CCTypes')
.then(res => res.json())
.then(res => {
this.cctypes = res.data;
});
}
}
};
</script>
The problem is, that there is no filling in the table.
maybe it's the double .then()... in your fectch method ... you should console.log your data first ...

Retrieve data using axios vue.js

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 !!");
});
},

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

how to create Pagination in Vue laravel table

I'm newbie in vue.js in laravel. I have a array data that display in table in vue. I want to create pagination for every 15 data. how can I do this? Any idea ?
template in vue.
<tbody>
<tr v-for="booking in bookings">
<td>{{ booking.booking_number | formatBookingNumber }}</td>
<td>{{ booking.date }}</td>
<td>{{ booking.status }}</td>
<td>{{ booking.check_in_date }}</td>
<td>{{ booking.check_out_date }}</td>
<td>
</td>
</tr>
</tbody>
Vue.js
<script>
export default {
props: ['bookings'] ..................
Amendments and additions
In case you haven't implemented a REST endpoint I suggest doing it with Transformers. After that you may follow the next use case:
app/Transformer/BookingsTransformer.php
public function transform($booking) {
return [
'booking-id' => $booking->booking_id,
'booking-data' => $booking->booking_date,
'booking-status' => $booking->booking_status,
'checkin' => $booking->booking_checkin,
'checkout' => $booking->booking_checkout,
];
}
app/Http/Controllers/BookingsResourceController.php
use EllipseSynergie\ApiResponse\Contracts\Response;
use App\Models\Bookings;
use App\Transformer\BookingsTransformer;
class ImageController extends Controller
{
protected $response;
public function __construct(Response $response)
{
$this->response = $response;
}
public function index()
{
//Get dataset's items
$image = Bookings::paginate(10);
// Return a collection of $images
return $this->response->withPaginator($image, new BookingsTransformer());
}
app/Http/Controllers/BookingsController.php
use App\Models\Bookings;
use Illuminate\Http\Request;
class BookingsController extends Controller
{
public function index()
{
return view('reservations');
}
routes/api.php
Route::get('bookings-api','ImageController#index');
routes/web.php
Route::get('/Bookings','BookingsController#index','as' => 'reservations');
resources/views/reservations.blade.php
<div class="container" id='app'>
<reservation-list></reservation-list>
</div>
Meanwhile you have to install npm and a pagination package in your Laravel project:
npm install
npm install vuejs-paginate --save
npm run watch
resources/assets/js/app.js
require('./bootstrap');
window.Vue = require('vue');
Vue.component(
'image-list',
require('./components/Bookings.vue')
);
Vue.component('paginate', require('vuejs-paginate'));
const app = new Vue({
el: '#app'
})
resources/assets/js/Components/Bookings.vue
<template>
<tbody>
<tr v-for="booking in bookings">
<td>{{ booking.booking_number | formatBookingNumber }}</td>
<td>{{ booking.date }}</td>
<td>{{ booking.status }}</td>
<td>{{ booking.check_in_date }}</td>
<td>{{ booking.check_out_date }}</td>
</tr>
</tbody>
<div class="centered">
<paginate
:page-count="pageCount"
:margin-pages="2"
:page-range="4"
:initial-page="0"
:container-class="'pagination'"
:click-handler="fetch"
:prev-text="'Prev'"
:next-text="'Next'"
></paginate>
</div>
</template>
<script>
export default {
data() {
return {
bookings: [],
endpoint: 'api/bookings-api'
};
},
created() {
this.fetch();
},
methods: {
fetch(page = 1) {
axios.get(this.endpoint + page)
.then(({data}) => {
this.dataset = data.data;
this.pageCount = data.meta.pagination.total_pages;
});
},
}
}
</script>
Hope it helped
you can try Vue Datatable package for this:
In your vue laravel application, you need to run below command just:
npm install --save vue-good-table
For more check this link:
Vue Laravel Tutorial Part 7 – Datatables
I am going to show you how to do it in simple way.Of course you need to change or add code to make this works in your app.Just try to understand the logic.
Vue.js component:
<template>
.....//here supposed to have more code
<tbody>
<tr v-for="booking in bookings">
<td>{{ booking.booking_number | formatBookingNumber }}</td>
<td>{{ booking.date }}</td>
<td>{{ booking.status }}</td>
<td>{{ booking.check_in_date }}</td>
<td>{{ booking.check_out_date }}</td>
<td>
</td>
</tr>
</tbody>
...
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
bookings: [],
page: 1, //change the page regarding your next and previous pagination button
rowsPerPage: 15,
totalItems: 0
.....
}
},
created () {
axios.get('/bookings', {
params: {
page: this.page,
rowsPerPage: this.rowsPerPage
}
})
.then(response => {
this.bookings = response.data.bookings
this.totalItems = response.data.totalItems
})
}
}
</script>
In Laravel routes/api.php
Route::get('/bookings','ControllerName#controllerFunctionName');
Then in your function,in your Controller do the following:
$page = $request->get('page');
$rowsPerPage = $request->get('rowsPerPage');
$skip = ($page - 1) * $rowsPerPage;
$bookings = YouBookingsModel::select(here put your query)->skip($skip)->take($rowsPerPage)->get();
$bookingsCount = YouBookingsModel::all()->count();
return response()->json([
"bookings" => $bookings,
"totalItems" => $bookingsCount
], 200);
Note that you have to made it in your own. But also consider using a material frameworks. I am using Vuetify which is awesome!!And there go to dataTables and you can use your table with pagination in easy and vuetiful way

Resources