Is there a way to update my component dynamically without refreshing the page? - laravel

I have a vue component which builds the card up, and within that component is another component that I pass data to with a prop I currently use Swal to as a popup to add a new project to the database however when it finishes adding I have to refresh the page for the data to be visible. The entire reason I wanted to use vue was to not have to refresh the page to view updated data and I haven't been able to figure it out.
This is my Projects.vue
import ProjectItem from './Projects/ProjectItem.vue';
export default {
name: "Projects",
components: {
ProjectItem
},
data() {
return {
projects: []
}
},
methods: {
getProjects () {
axios.get('/api/projects').then((res) => {this.projects = res.data});
},
addProject() {
Swal.queue([{
title: 'Add a New Project?',
html:
'<label for="name" style="color: #000;font-weight: 700">Project Name<input id="name" class="swal2-input"></label>' +
'<label for="description" style="color: #000;font-weight: 700">Project Description<textarea id="description" rows="5" cols="15" class="swal2-input"></textarea></label>',
showCancelButton: true,
confirmButtonText: 'Create Project',
showLoaderOnConfirm: true,
preConfirm: (result) => {
return new Promise(function(resolve, reject) {
if (result) {
let name = $('#name').val();
let desc = $('#description').val();
axios.post('/api/projects', {title:name,description:desc})
.then(function(response){
Swal.insertQueueStep({
type: 'success',
title: 'Your project has been created!'
})
resolve();
})
.catch(function(error){
Swal.insertQueueStep({
type: 'error',
title: 'Something went wrong.'
})
console.log(error);
reject();
})
}
});
}
}])
}
},
mounted () {
this.getProjects();
}
I bind it to ProjectItem in my Project.vue template:
<div class="table-responsive border-top">
<table class="table card-table table-striped table-vcenter text-nowrap">
<thead>
<tr>
<th>Id</th>
<th>Project Name</th>
<th>Team</th>
<th>Date</th>
<th>Preview</th>
</tr>
</thead>
<project-item v-bind:projects="projects" />
</table>
and this is my ProjectItem.vue:
<template>
<tbody>
<tr v-for="project in projects" :key="project.id">
<td>{{ project.id }}</td>
<td>{{ project.title }}</td>
<td><div class="avatar-list avatar-list-stacked">
{{ project.description }}
</div>
</td>
<td class="text-nowrap">{{ project.updated_at }}</td>
<td class="w-1"><i class="fa fa-eye"></i></td>
</tr>
</tbody>
</template>
<script>
export default {
name: "ProjectItem",
props: ["projects"],
}
</script>

You must insert the recently added project to the products array.
If you are able to change the backend code, you could change the response to include the project.
this.projects.push(response.project);

Related

Using v-for in laravel + vue.js, am trying to display a table containing information of the user but nothing shows

<script>
export default {
name: "OutPatient",
data(){
return{
out_patients: {}
}
},
methods: {
index(){
axios.get('/data/out_patient').then(({data}) =>
(this.out_patients = data.data));
},
update(){}
},
created(){
this.index();
}
}
</script>
<tr v-for="out_patient in out_patients" v-bind:key="out_patient.id">
<td>{{out_patient.id}}</td>
<td>{{out_patient.first_name}}</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
<i class="fa fa-edit blue"></i>
|
<i class="fa fa-trash red"></i>
</td>
</tr>
This is my code but the data is not showing in the table even though in the XHR the data shows there.
In the inspect element I can see the data but the v-for loop is unable to display the data.
Seems to me like you tried to extract data twice, you have this:
axios.get('/data/out_patient').then(({data}) =>
(this.out_patients = data.data));
if you already extract it here: {data} then you don't need data.data, only data below?
index() {
this.error = this.out_patients = null;
this.loading = true;
axios
.get('/data/out_patient')
.then(response => {
this.loading = false;
this.out_patients = response.data;
}).catch(error => {
this.loading = false;
this.error = error.response.data.message || error.message;
});
},
this rather works for me.
thank you all for the support
can you try fetching the data on mounted life cycle hook instead of created in order to populate the table with data on page load mounted is the best hook lifecycle as much I know.
<script>
export default {
name: "OutPatient",
data(){
return{
out_patients: {},
out_patient:'',
}
},
methods: {
index(){
axios.get('/data/out_patient')
.then(({data}) =>
(this.out_patients = data.data));
},
update(){
}
},
created(){
this.index();
}
}
</script>
<tr v-for="out_patient in out_patients" v-bind:key="out_patient.id">
<td>{{out_patient.id}}</td>
<td>{{out_patient.first_name}}</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
<a href="#">
<i class="fa fa-edit blue"></i>
</a>
|
<a href="#">
<i class="fa fa-trash red"></i>
</a>
</td>
</tr>
Just declare out_patient in data. I hope this solves your issue.
And also check if out_patients is returning data.

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({});
});
});

How to showing data on table with datatables 'yajra'

I following this tutorial : How to route in Laravel DataTables
its so simple , but i cant do it . after i set my controller and my route and view , its not showing data and and table. in the table i have a button like'action' how i can take this comand to this button ?
can you check my faulth query
Route::get('user/show1', 'userController#show')->name('usershow1');
Route::get('user/show1-dt', 'userController#indexDataTables')->name('usershow1dt');
controller
public function show()
{
$pemeliharaan = Pemeliharaan::with(['user','alat'])->where('status','harian')->get();
return view('users.view_harian',['pemeliharaan' => $pemeliharaan]);
}
public function indexDataTables()
{
$pemeliharaan = Pemeliharaan::query();
// return DataTables::eloquent($pemeliharaan)->toJson();
return Datatables::of($pemeliharaan)->make(true);
}
and i have a view like this . the page number,search and pagination is showing at view ,but this data not showing. can you correctted this view ?
<div class="box-body table-responsive no-padding">
<table class="table table-hover" id="table">
<tbody><tr>
<th>No</th>
<th>Nama Alat</th>
<th>status</th>
<th>User Input</th>
<th>Action</th>
<th>Tanggal</th>
</tr>
{{-- #php ---> before i suing datatables my view like that
$no=0;
#endphp
#foreach ($pemeliharaan as $i)
<tr>
<td>{{ ++$no }} </td>
<td>{{ $i->alat->nama_alat}}</td>
<td>{{ $i->status}}</td>
<td>{{ $i->user->name}}</td>
<td> Lihat Data</span> </td>
<td>{{ $i->created_at}}</td>
</tr>
#endforeach --}}
</tbody></table>
</div>
.
.
#endsection
#push('scripts')
<script>
$(function() {
$('#table').DataTable({
processing: true,
serverSide: true,
ajax: '{!! route('usershow1dt') !!}',
columns: [
{ data: 'nama_alat', name: 'nama_alat'},
{ data: 'status', name: 'status'},
{ data: 'User Input', name: 'nama'},
{ data: 'Action', name: 'name'},//here my button
{ data: 'Tanggal', name: 'created_at'},
],
});
})
</script>
#endpush
Try This:
public function show() {
$pemeliharaan = Pemeliharaan::where('user','alat')->where('status','harian')->get();
return view('users.view_harian',['pemeliharaan' => $pemeliharaan]);
}

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 ...

Checkbox doesn't save true value

I'm using Laravel 5.6 and Vuejs 2.
If I click on my checkbox and make the value true it's supposed to save a 1 in the database and if I click my checkbox and make the value false it saves a 0.
The problem I'm having is that if I click my checkbox and make it true, it doesn't save the correct value, no changes is made to the database and I don't get any errors. If I click on my checkbox and make it false, it saves the 0 correctly.
I did notice that even when my value is supposed to be true, I do get a false when I dd($category->has('active')
I'm not sure where I'm going wrong or how to fix it.
My vue file
<template>
<div class="card-body">
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">Active</th>
<th scope="col">Title</th>
<th scope="col">Edit</th>
<th scope="col">Delete</th>
</tr>
</thead>
<tbody>
<tr v-for="(category, index) in categoriesNew" >
<td>
<label>checkbox 1</label>
<input name="active" type="checkbox" v-model="category.active" #click="checkboxToggle(category.id)">
</td>
<td>
{{ category.title }}
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
props: ['categories'],
data(){
return {
categoriesNew: this.categories
}
},
methods: {
checkboxToggle(id){
console.log(id);
axios.put('/admin/category/active/'+id, {
categories: this.categoriesNew
}).then((response) => {
//Create success flash message
})
},
},
mounted() {
console.log('Component mounted.')
}
}
</script>
my routes
Route::put('admin/products/updateAll', 'Admin\ProductsController#updateAll')->name('admin.products.updateAll');
Route::put('admin/category/active/{id}', 'Admin\CategoryController#makeActive')->name('admin.category.active');
Route::resource('admin/category', 'Admin\CategoryController');
Route::resource('admin/products', 'Admin\ProductsController');
my CategoryController#makeActive
public function makeActive(Request $request, $id)
{
$category = Category::findOrFail($id);
if($request->has('active'))
{
$category->active = 1;
}else{
$category->active = 0;
}
$category->save();
}
I hope I made sense. If there is anything that isn't clear or if you need me to provide more info, please let me know
Try changing this line
categories: this.categoriesNew
to
categories: category.active
and add a data prop at the top called category.active: ''
I've managed to get it to work. This is what I did.
vue file
<template>
<div class="card-body">
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">Active</th>
<th scope="col">Title</th>
<th scope="col">Edit</th>
<th scope="col">Delete</th>
</tr>
</thead>
<tbody>
<tr v-for="(category, index) in categories" >
<td>
<label>checkbox 1</label>
<input type="checkbox" v-model="category.active" #click="checkboxToggle(category)">
</td>
<td>
{{ category.title }}
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
props: ['attributes'],
data(){
return {
categories: this.attributes,
}
},
methods: {
checkboxToggle (category) {
axios.put(`/admin/category/${category.id}/active`, {
active: !category.active
}).then((response) => {
console.log(response)
})
}
},
mounted() {
console.log('Component mounted.')
}
}
</script>
my routes
Route::put('admin/category/{category}/active', 'Admin\CategoryController#makeActive')->name('admin.category.active');
and my CategoryController#makeActive
public function makeActive(Request $request, $id)
{
$category = Category::findOrFail($id);
if(request('active') === true)
{
$category->active = 1;
}else{
$category->active = 0;
}
$category->save();
}

Resources