how to reload table when certain row is created or delete? - laravel

I am just learning Vuejs with laravel. and my Delete is Working correctly but when it redirect to index page after row is deleted that row is not removed until it is loaded..
And for When Category is added new data is not shown until browser is loaded...
This is my Categories Component `
<form role="form" method="POST" enctype="multipart/form-data" #submit.prevent="createCategory" v-if="adding">
<div class="card-header">
<h3 class="card-title">Create New Category</h3>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Category Name</label>
<input type="text" class="form-control" id="category_name" v-model="category_name" placeholder="Enter Category Name">
</div>
</div>
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-primary">Submit</button>
<button #click.prevent="cancel" class="btn btn-danger">Cancel</button>
</div>
</form>
<div class="card-body" v-else>
<div class="card-header" >
<h3 class="card-title"><a class="btn btn-block btn-outline-secondary btn-lg" #click.prevent="add()"> Create New Category</a></h3>
</div>
<table id="example2" class="table table-bordered table-hover" >
<head>
<tr>
<th>ID</th>
<th>Category Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr v-for="(category,index) in model" :category="category" v-bind:key="category.id">
<td>{{category.id}}</td>
<td>{{category.category_name}}</td>
<td>Edit | <a #click="deleteCategory(category.id,index)" class="btn-outline-
danger">Delete</a></td>
</tr>
</body>
</table>
</div>
</div>
`
<script>
export default {
props:['model'],
data(){
return {
model:[],
section_id: 0,
sections: [],
parent_id: 0,
categories: [],
adding:false,
category_name:'',
}
},
methods:{
add(){
this.adding=true;
},
cancel(){
this.adding=false;
},
createCategory(){
axios.post(`categories `,{
category_name:this.category_name,
}).catch(error => {
console.log('Error')
})
.then(res=>{
this.adding=false;
})
},
deleteCategory(id,index){
if(confirm('Are You Sure ?')){
axios.delete('categories/'+id)
.then(resp => {
this.model.splice(index, 1);
})
.catch(error => {
console.log(error);
})
}
}
},
}
</script>

<table id="example2" v-if="flag" class="table table-bordered table-hover" >
<head>
<tr>
<th>ID</th>
<th>Category Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr v-for="(category,index) in model" :category="category" v-bind:key="category.id">
<td>{{category.id}}</td>
<td>{{category.category_name}}</td>
<td>Edit | <a #click="deleteCategory(category.id,index)" class="btn-outline-
danger">Delete</a></td>
</tr>
</body>
</table>
in data add flag:false,
data(){
return {
model:[],
section_id: 0,
sections: [],
parent_id: 0,
categories: [],
adding:false,
category_name:'',
flag:false
}
},
in your functions make your flag false in case of success response
deleteCategory(id,index){
this.flag=false;
if(confirm('Are You Sure ?')){
axios.delete('categories/'+id)
.then(resp => {
this.model.splice(index, 1);
this.flag=true;
})
.catch(error => {
console.log(error);
this.flag=false;
})
}
}

I think that you are overcomplicate this. Just create an API that retrieve all the categories. So after each addition or deletion, then just call that API.

Related

How to make filter on table based on option select

I am working on a project (vue + laravel) where i need to fetch all table structure from db. So my table will be dynamically with all field(table header) and record. Now i need to do a filter(search) for each visible column. I have tryed some way but it does not work for me, I just dont know how to pass only column value for each option select value.
Collapse content is the option who will show on filter click and there should display the option for each column
<table class="table table-hover align-middle mb-0" :class="smallTable.smTable">
<thead class="">
<tr>
<th><input type="checkbox" class="form-check-input" v-model="selectAll" title="Select All"></th>
<th v-for="(header, i) in visibleHeaders" :key="i" scope="col">
{{ header.name }}
</th>
<th v-if="actionHide">ACTION</th>
</tr>
</thead>
<!-- Collapsed content ./ -->
<thead class="collapse" id="collapseFilter">
<tr>
<th></th>
<th v-for="(header, i) in visibleHeaders" :key="i">
<div class="filter-table col-12 d-flex">
<select id="" class="form-select" >
<option v-for="(lead, i) in leads" >{{lead}}</option>
</select>
</div>
</th>
</tr>
</thead>
<!-- ./ Collapse contet -->
<tbody>
<tr v-show="leads.length" v-for="(lead, i) in leads" :key="i">
<td>
<input type="checkbox" class="form-check-input" v-model="selected" :value="lead.id" />
</td>
<td v-for="(field, j) in lead" :key="j">
<span v-if="field == 'new'" class="badge badge-primary">
{{ field }}
</span>
<span v-else-if="field == 'contract'" class="badge badge-success">
{{ field }}
</span>
<span v-else>
{{ field }}
</span>
</td>
<td >
<button #click="editLead(lead.id)" type="button" class="btn btn-sm btn-secondary" data-mdb-toggle="modal" data-mdb-target="#editLeadModal" >
<i class="fa-solid fa-eye"></i>
</button>
</td>
</tr>
<tr v-show="!leads.length">
<td colspan="12" class="text-center">Sorry :( No data found.</td>
</tr>
</table>
data() {
return {
headers: [],
leads: [],
fields: [],
}
}
mounted() {
axios.get('/leads/getfields')
.then(response => {
this.fields = response.data.map(field => {
return {
name: field,
visible: true,
}
});
}
this.getData();
});
}
getData() {
this.headers = this.fields.map(item => {
if (item.visible) {
return item.name;
}
});
axios.post('/leads/getleads?page=' + this.pagination.current_page, {
perPage: this.displayRecord,
fields: this.headers,
})
.then(response => {
this.leads = response.data.data;
this.pagination = response.data.meta
});
},

Update Column Value with the help of vue js in laravel

This is my blade of laravel
<!-- Main Container -->
<main id="main-container">
<!-- Page Content -->
<div class="content" id="app">
<h2 class="content-heading">Accessory Details</h2>
<div class="block block-themed">
<div class="block-header block-header-default">
<div class="block-options">
<button class="btn btn-success pull-right">New Request</button>
</div>
</div>
<div class="block-content">
<form action="" method="get">
<div class="form-group row">
<label class="col-12" for="example-select2-multiple">Store Location</label>
<div class="col-lg-11">
<select class="form-control" name="store" style="width: 100%;" required>
<option value="">Choose Select Store location..</option>
#foreach($stores as $store)
<option #if($store_selected == $store->id) selected #endif value="{{ $store->id }}">{{ $store->channel_id }} | {{ $store->street_name }}</option>
#endforeach
</select>
</div>
<div class="col-1">
<button type="submit" class="btn btn-alt-success">
Filter
</button>
</div>
</div>
</form>
</div>
</div>
<!-- Dynamic Table Full -->
<div class="block">
<div class="block-content block-content-full">
#include('errors.error')
<div class="table-responsive">
<table class="table table-bordered table-striped table-vcenter js-dataTable-full1" data-page-length='50'>
<thead>
<tr>
<th class="text-center">#</th>
<th class="text-center">User</th>
<th>Store</th>
<th class="">Request Date</th>
<th class="">Status</th>
<th class=""></th>
</tr>
</thead>
<tbody>
#foreach($accessories as $accessory)
<tr>
<td>{{ $accessory->id }}</td>
<td>{{ $accessory->user->name }}</td>
<td>{{ $accessory->store->channel_id }} - {{ $accessory->store->street_name }}</td>
<td>{{ $accessory->request_date }}</td>
<td>{{ $accessory->status }}</td>
<td><button class="btn btn-primary btn-sm" #click="getdetails({{ $accessory->id }})" data-toggle="modal" data-target="#details">Details</button></td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
<!-- END Dynamic Table Full -->
<b-modal id="modal-1" title="Details" v-model="dialog" #ok="handleOk">
<form ref="form" #submit.stop.prevent="handleSubmit">
#csrf
{{-- <input type="hidden" v-model="id"/> --}}
<select class="form-control" name="status">
<option>Pending</option>
<option>Ordered</option>
<option>Received</option>
</select>
<br><br>
<table class="table table-bordered">
<tr>
<td>Vendor</td>
<td>Description</td>
<td>QTY</td>
</tr>
<tr v-for="line in lines">
<td>#{{line.name}}</td>
<td>#{{line.description}}</td>
<td>#{{line.qty}}</td>
</tr>
</table>
</form>
</b-modal>
</div>
</main>
<script >
window.app = new Vue({
el: '#app',
mounted: function() {
},
data() {
return {
dialog: false,
lines: [],
}
},
methods: {
getdetails: function(id) {
let self = this;
this.lines = [];
axios.get('/accessory/' + id)
.then(response => {
this.dialog = true;
self.lines = response.data;
console.log(self.lines)
//$(location).attr('href', '/accessory')
})
.catch(function (error) {
alert('Error');
});
},
handleOk(bvModalEvt) {
// Prevent modal from closing
bvModalEvt.preventDefault()
// Trigger submit handler
this.handleSubmit()
},
handleSubmit() {
axios.post('/accessory/status-change/' )
.then(response => {
$(location).attr('href', '/accessory')
})
.catch(function (error) {
alert('Error');
});
}
},
created()
{
}
})
</script>
<script>
$(document).ready(function() {
$('.js-dataTable-full1').DataTable( {
"order": [[ 0, "desc" ]]
} );
});
</script>
Here for the following statement in model , i want to bind it with accessory_request_id which i am recieving {{-- --}}. So what should i select for v-model?
If i check for console.log(self.lines), it returns me an array with accessory_request_id.
Then later on with the help of accessory_reques_id, i want to update status in database.
So follow is my controller code --
{
//return 'test';
//dd($request->all());
$accessory_request = AccessoryRequest::findorfail($request->id);
$accessory_request->status = $request->input('status');
$accessory_request->save();
return ['message' => 'Status Updated'];
}
In web.php -- route is
Route::post('accessory/status-change','AccessoryController#status_change');
please help me to resolve it

How to auto-populate form fields using vue and laravel

I'm developing a web application where I want to populate some field if I type computer_number I want to populate staff_old_name field that will select from staffs table.
This is what I've tried:
Template
<div>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>Computer Number</th>
<th>Old Name</th>
<th>New Name</th>
<th>Remarks</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr v-for="(staff, index) in staffs">
<td>
<span v-if="staff.editmode"><input class="form-control" v-model="staff.computer_number"/></span>
<span v-else>{{staff.computer_number}}</span>
</td>
<td>
<span v-if="staff.editmode"><input class="form-control" v-model="staff.old_name"/></span>
<span v-else>{{staff.old_name}}</span>
</td>
<td>
<span v-if="staff.editmode"><input class="form-control" v-model="staff.new_name"/></span>
<span v-else>{{staff.new_name}}</span>
</td>
<td>
<span v-if="staff.editmode"><input class="form-control" v-model="staff.remarks"/></span>
<span v-else>{{staff.remarks}}</span>
</td>
<td>
<span v-if="!staff.editmode"><button class="btn btn-info" type="button" #click="edit(staff)">Edit</button></span>
<span v-else><button class="btn btn-success" type="button" #click="save(staff)">Save</button></span>
<span><button type="button" class="btn btn-danger" #click="remove(index)"><i class="fa fa-trash"></i></button></span>
</td>
</tr>
</tbody>
</table>
<div class="box-footer">
<button class="btn btn-info" type="button" #click="cloneLast">Add Row</button>
</div>
</div>
Script
export default {
data() {
return {
staffs: [],
data_results: []
}
},
computed:{
autoComplete(){
this.data_results = [];
if(this.computer_number.length > 2){
axios.get('/api/staffs/autocomplete',{params: {computer_number: this.computer_number}}).then(response => {
console.log(response);
this.data_results = response.data;
});
}
}
},
methods: {
edit :function(obj){
this.$set(obj, 'editmode', true);
},
save : function(obj){
this.$set(obj, 'editmode', false);
},
remove: function(obj){
this.staffs.splice(obj,1);
},
cloneLast:function(obj){
//var lastObj = this.staffs[this.staffs.length-1];
//lastObj = JSON.parse(JSON.stringify(lastObj));
obj.editmode = true;
this.staffs.push(obj);
},
},
created() {
axios.get('/staff-names')
.then(response => this.staffs = response.data);
},
}
when I type the computer number I want the staff_old_name field populated base on staff name which is stored in staffs table.

sum score in ajax not working with laravel5.4

I have score field in table of infractions. And I have many checkboxes. When I checked the chechboxes, The total of scores are collected with ajax.
<div class="panel-body">
<div class="table-responsive">
<table class="table table-bordered">
#foreach($infractions as $infraction)
<tr>
<th>{{ $infraction->title }}</th>
<td>
<input type="checkbox" data-toggle="toggle" data-on="Yes" data-off="No" data-onstyle="success" data-offstyle="danger" data-score="{{ $infraction->score }}" onClick="updateTotal();">
</td>
</tr>
#endforeach
</table>
</div>
<div class="text-right">Total:
<span id="total">
</span>
</div>
</div>
Ajax
function scorePlus (id)
{
var total = id + id;
document.getElementById('total').value = total;
}
This should work
<div class="panel-body">
<div class="table-responsive">
<table class="table table-bordered">
#foreach($infractions as $infraction)
<tr>
<th>{{ $infraction->title }}</th>
<td>
<input type="checkbox" data-score="{{ $infraction->score }})" onClick="updateTotal();">
</td>
</tr>
#endforeach
</table>
</div>
<div class="text-right">Total:
<span id="total">0</span>
</div>
</div>
<script>
function updateTotal() {
var checked = document.querySelectorAll('input[type=checkbox]:checked');
var score = 0;
Array.prototype.forEach.call(checked, function(el, i){
score += parseInt(el.getAttribute('data-score'));
});
document.getElementById('total').innerHTML = score;
}
</script>

knockoutjs $parent undefined

I have a problem with KnockoutJS, where the $parent binding context is undefined.
Code
<div class="row">
<div class="col-md-4">
<div class="panel panel-info">
<div class="panel-heading">
<h2 class="panel-title">Products Data</h2>
</div>
<div class="panel-body">
<table class="table table-striped table-bordered table-condensed" data-bind="with: ProductsViewModel">
<thead>
<tr>
<th>ProductID</th>
<th>Product Name</th>
<th>Units In Stock</th>
<th>Action</th>
</tr>
</thead>
<tbody data-bind="foreach: products">
<tr>
<td data-bind="text: $data.ProductID"></td>
<td data-bind="text: $data.ProductName"></td>
<td data-bind="text: $data.UnitsInStock"></td>
<td><button class="btn btn-danger btn-xs" data-bind="click: $parent.RemoveProduct">[x] delete</button></td>
</tr>
</tbody>
</table>
<button class="btn btn-large" data-bind="click: GetProducts()">Load Data</button>
</div>
</div>
</div>
</div>
and:
/// <reference path="../Scripts/knockout-3.4.0.js" />
/// <reference path="../Scripts/jquery-1.10.2.js" />
function ProductsViewModel() {
var self = this;
self.products = ko.observableArray([]);
self.RemoveProduct = function () {
bootbox.alert({ message: 'Pressed !!', size: 'small' });
}
self.GetProducts = function () {
self.products.removeAll();
$.getJSON('/api/products', function (data) {
$.each(data, function (key, value) {
self.products(data);
});
});
}
}
$(document).ready(function () {
ko.applyBindings(ProductsViewModel);
});
All the binding work correctly in the table, except the click event binding on the button, where the $parent is undefined.
If I remove the button control all the data binds correctly in the table element.
Any ideas how to fix this ?? It's all standard Knockout code to my knowledge.
Thanks in advance.
bax2097
I've fixed this by removing the $parent altogether. All working now.
Problems
In your Html you bind your table into a with: ProductsViewModel. Which is not needed.
In your Load data button you did not pass the actual function, instead you execute it right away, so just remove ().
See this JsFiddle for demo

Resources