How to count v-for object with if condition - laravel

I try to count totalPaids(transaction.paid).
vue component:
<tr v-if="studentFees" v-for="(studentFee, index) in studentFees">
<td style="text-align: center;">{{ index+1 }}</td>
<td style="text-align: center;">{{ studentFee.programe }}</td>
<td style="text-align: center;">{{ studentFee.level }}</td>
<td style="text-align: center;">{{ studentFee.course_fee }}</td>
<td style="text-align: center;">{{ studentFee.student_amount }}</td>
<td style="text-align: center;">{{ studentFee.discount }}</td>
<div v-for="studentTransaction in studentTransactions">
<div v-if="studentTransaction.s_fee_id == studentFee.s_fee_id">
<td style="text-align: center;">{{ totalPaids(studentTransaction.paid) }}</td>
</div>
</div>
</tr>
or see https://i.stack.imgur.com/aGoLo.png
in vue method:
totalPaids(values){
console.log(values)
}
console.log: 3000, 5000, 2000, 1000
please help to sumation.

Working snippet:
new Vue({
el: '#app',
data: {
message: 'p',
sum:0
},
methods:{
totalPaids: function(values){
this.$data.sum+= Number(values);
console.log( this.$data.sum);
return this.$data.sum;
}
},
mounted(){
for(var i=0;i<5;i++)
this.message=this.totalPaids(900);
}
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
<p>{{ message }}</p>
</div>
I would suggest you to register the variable in the data section to save it's state:
data: {
sum: 0,
},
Later modify the method totalPaids like this:
totalPaids(values){
this.sum+= Number(values);
console.log(sum);
return sum;
}
Hope this helps.

Assuming your values is an array of numbers then you can use the reduce method in JavaScript. So you can adjust your TotalPaid function to this:
totalPaids(values){
var sum = values.reduce((sum, currentVal) => sum + currentVal);
console.log(sum);
return sum;
}
So this just takes your array of values, then runs through them adding the current value to the sum value each time.

Related

change datatable data after ajax sucess ( as per Selection box)

I am new to Laravel and coding and stuck at point where i want to change to data table data (tbody) as per selection box value. The code is as below.
On Page load table shows data as per default selection. After ajax success, alert is showing the correct data
Selection box
<div class="form-inline">
<label><strong>Select Option :</strong></label>
<select id='selectoption' class="form-control" style="width: 150px">
<option value="material">By Material</option>
<option value="supplier">By Supplier</option>
</select>
</div>
Table
<table id="expensestable" class="table table-bordered table-hover" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th>Material / Supplier</th>
<th>From Date</th>
<th>To Date</th>
<th>Total Quantity</th>
<th>Total Amount</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach ($expdatabymaterial as $i )
<tr>
<td>{{$i->materialid}}</td>
<td>{{$i->material}}</td>
<td>{{ date('d-m-Y', strtotime ($startdateofmonth)) }}</td>
<td>{{ date('d-m-Y', strtotime ($enddateofmonth)) }}</td>
<td>{{$i->totalquantity}}</td>
<td>{{$i->totalamount}}</td>
<td>
<button type="button" class="deletedatabtn btn btn-primary"><i class="far fa-eye" title="View"></i></button>
</td>
</tr>
#endforeach
</tbody>
</table>
Ajax
$('#selectoption').change( function() {
var selectoption = $(this).find('option:selected').val();
var token = "{{ csrf_token() }}";
$.ajax({
type: 'post', //'POST'
url: '/changeselection',
data: { option: selectoption, _token: token, },
success: function (data) {
alert(data)
}
});
});
Controller
$startdateofmonth = new Carbon('first day of this month');
$enddateofmonth = new Carbon('last day of this month');
if ($req->get('option') == 'material')
{
$expdatabymaterial = Dairyexpense::selectraw('material, material, materialid, materialid, SUM(quantity) as "totalquantity", SUM(totalamount) as "totalamount"')
->whereBetween('expensesdate', [$startdateofmonth, $enddateofmonth])
->groupBy('material','materialid')->get();
return response([$expdatabymaterial]);
}
else
{
$expdatabysuuplier = Dairyexpense::selectraw('supplier, supplier, supplierid, supplierid, SUM(quantity) as "totalquantity", SUM(totalamount) as "totalamount"')
->whereBetween('expensesdate', [$startdateofmonth, $enddateofmonth])
->groupBy('supplier','supplierid')->get();
return response([$expdatabysuuplier]);
}
Thanks in advance for support and help.....

Laravel datatables can't create custom columns

I have two tables first one simple html with no datatables, second with datables. My purpose transform first table two datatables second. But I had two main problems Grazinimo terminas column is using laravel #if and column Veiksmai using if statemens as well how can i add those as custom columns in second table.
First table code
<table class="table table-bordered">
<thead class="bg-warning">
<th>Knygos pavadinimas</th>
<th>Miestas</th>
<th>Išdavimo data</th>
<th>Grąžinimo terminas</th>
<th>Vardas</th>
<th>Pavardė</th>
<th>Kliento nr.</th>
<th>Veiksmai</th>
</thead>
<tbody>
#foreach($paskolinimai as $p)
<input type="hidden"
value="{{ $skirtumas = \Carbon\Carbon::parse(\Carbon\Carbon::today()->toDateString())->diffInDays( \Carbon\Carbon::parse( $p->terminas),false) }}">
<tr>
<td>{{ $p->pavadinimas }}</td>
<td>{{ $p->miestas }}</td>
<td>{{ $p->isdavimo_data }}</td>
#if($p->grazinimo_data != NULL)
<td>
<strong style="color: green;">Knyga grąžinta!</strong>
</td>
#elseif($skirtumas > 0)
<td>
Liko <strong style="color: crimson;">{{ $skirtumas }}</strong> dienų.
</td>
#elseif($skirtumas < 0) <td>
<strong style="color: crimson;">Terminas praėjo!</strong>
</td>
#elseif($skirtumas = 0)
<td>
<strong style="color: crimson;">Šiandien paskutinė grąžinimo diena!</strong>
</td>
#endif
<td>{{ $p->vardas }}</td>
<td>{{ $p->pavarde }}</td>
<td>{{ $p->klientasnr }}</td>
#if($p->grazinimo_data == null)
<td><a href="{{ url('patvirtinti-grazinima-'.$p->id.'-'.$p->bookid) }}"
class="btn btn-primary">Grąžinimas</a> </td>
#else
<td>
<p class="btn btn-success">Grąžinta</p>
</td>
#endif
#endforeach
</tr>
</tbody>
</table>
Second table code
<script>
$(document).ready(function () {
var darbuotojai = $('#paskolinimai').DataTable({
processing: true,
serverSide: true,
ajax:
{
url: '{!! route('get.paskolinimai') !!}'
},
columns: [
{ data: 'pavadinimas', name: 'pavadinimas' },
{ data: 'miestas', name: 'miestas' },
{ data: 'isdavimo_data', name: 'isdavimo_data' },
{ data: 'vardas', name: 'vardas' },
{ data: 'pavarde', name: 'pavarde' },
],
'oLanguage': {
'sSearch': "Paieška:",
'sZeroRecords': "Nerasta atitinkančių įrašų",
'sLengthMenu': "Rodyti _MENU_ įrašų",
'sInfo': "Nuo _START_ iki _END_ viso _TOTAL_ įrašų",
'sProcessing': "Apdorojama...",
'sLoadingRecords': "Kraunama...",
'sInfoFiltered': " - (filtruojama iš _MAX_ įrašų)",
'oPaginate': {
'sFirst': "Pirmas",
'sLast': "Paskutinis",
'sNext': "Sekantis",
'sPrevious': "Ankstesnis"
},
},
'sDom': '<"top"lfip>rt<"bottom"p><"clear">',
});
});
</script>
<table id="paskolinimai" class="table table-bordered">
<thead class="bg-warning">
<th>Knygos pavadinimas</th>
<th>Miestas</th>
<th>Išdavimo data</th>
<th>Vardas</th>
<th>Pavardė</th>
</thead>
<tbody></tbody>
</table>
</div>
So how can i add Grazinimo terminas and veiksmai correctly to the second table
I recommend you to use this package:
https://yajrabox.com/docs/laravel-datatables/master/installation
then go to section add column:
https://yajrabox.com/docs/laravel-datatables/master/add-column
and in your code will be like that:
->addColumn('intro', function(User $user) {
if($condtion){return $result}
})

[Vue warn]: Error in render: "TypeError: this.input.reduce is not a function" in Vue.js

i'm creating a very simple sum of Table of Amount by using computed in vuejs, but there is an issue come up
[Vue warn]: Error in render: "TypeError: this.input.reduce is not a function"
Still, i cant figure it out with my code.
// My Vue js
<pre>
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
<th>Current_id</th>
<th>Date</th>
<th>Description</th>
<th>Amount</th>
<th colspan="2">Modify</th>
</tr>
</thead>
<tbody>
<tr v-for="(user,key) in users">
<td>{{ user.user.name }}</td>
<td>{{ user.date }}</td>
<td>{{ user.description }}</td>
<td>${{ user.amount }}</td>
<td #click.prevent="editUser(key)">
<span class="btn btn-info">Edit</span>
</td>
<td #click.prevent="remove(user.id)">
<span class="btn btn-danger">Delete</span>
</td>
</tr>
</tbody>
</table>
</div>
<div>
<p>Total of Amount {{ total }}</p>
</div>
</pre>
// My Script file
<pre>
data() {
return {
users: [],
input: {
date: "",
description: "",
amount: ""
},
edit: false,
add: true,
}
},
computed: {
total() {
return this.input.reduce((total, item) => {
return total + item.amount;
}, 0);
}
},
</pre>
Any Help? Thanks...

table is not displaying, when i pull data from database

this is my table which is soppose to display subject details from the database
<div class="card-body table-responsive p-0">
<table class="table table-hover">
<tbody>
<tr>
<th>ID</th>
<th>Subject Code</th>
<th>Subject Name</th>
<th>Credit Hours</th>
<th>Created_at</th>
<th>Action</th>
</tr>
<tr v-for="subject in subjects" :key="subject.id">
<td>{{ subject.id }}</td>
<td>{{ subject.code | capitalize}}</td>
<td>{{ subject.name }}</td>
<td>{{subject.credit_hours}}</td>
<td>{{ subject.created_at |datetime }}</td>
<td>
<!-- Edit User -->
<a href="#" #click="editModal(subject)">
<i class="fa fa-edit text-green"></i>
</a>
<!-- Delete User -->
<a href="#" #click="deleteSubject(subject.id)">
<i class="fa fa-trash text-red"></i>
</a>
</td>
</tr>
this is my vuejs code to get data from subjectcontroller#index
<script>
import { Form, HasError, AlertError } from 'vform'
export default {
data () {
return {
editmode : false,
subjects: {}
form: new Form({
id: '',
subject_code: '',
subject_name: '',
credit_hours: '',
})
}
},
methods:{
loadSubjects(){
axios.get("api/subject")
.then(
({data}) => (this.subjects = data.data)
);
}
},
created(){
this.loadSubjects();
}
}
</script>
this is the code from subjectController#index
public function index()
{
$subjects = Subject::latest();
return $subjects->get();
}
the subject data displays in the consoles Network.XHR,
there are no console errors or warning
Any help will be appreciated
I was facing the same problem recently. Inside the axios module, try the following:
axios
.get("api/subject")
.then(response => (this.subjects = response.data));

Loading data when button is clicked using vue js and laravel

I have this project that when a user clicks on a button the data should be displayed on a table. However, I am using a table as seen here http://i.stack.imgur.com/HW4rE.jpg. What I want is that when a user clicks on the add button on the enrollment form table, it should displayed on the added subjects table without the need of refreshing the page. The problem is that I am using a table and I cannot make use of the v-model to bind the values.
So here's my form.blade.php
Enrollment Form table
<table class="table table-bordered">
<tr>
<th>Section</th>
<th>Subject Code</th>
<th>Descriptive Title</th>
<th>Schedule</th>
<th>No. of Units</th>
<th>Room</th>
<th>Action</th>
</tr>
<body>
<input type="hidden" name="student_id" value="{{ $student_id }}">
#foreach($subjects as $subject)
#foreach($subject->sections as $section)
<tr>
<td>{{ $section->section_code }}</td>
<td>{{ $subject->subject_code }}</td>
<td>{{ $subject->subject_description }}</td>
<td>{{ $section->pivot->schedule }}</td>
<td>{{ $subject->units }}</td>
<td>{{ $section->pivot->room_no }}</td>
<td>
<button
v-on:click="addSubject( {{ $section->pivot->id}}, {{ $student_id}} )"
class="btn btn-xs btn-primary">Add
</button>
<button class="btn btn-xs btn-info">Edit</button>
</td>
</tr>
#endforeach
#endforeach
</body>
</table>
AddedSubjects Table
<table class="table table-bordered">
<tr>
<th>Section Code</th>
<th>Subject Code</th>
<th>Descriptive Title</th>
<th>Schedule</th>
<th>No. of Units</th>
<th>Room</th>
<th>Action</th>
</tr>
<body>
<tr v-for="reservation in reservations">
<td>#{{ reservation.section.section_code }}</td>
<td>#{{ reservation.subject.subject_code }}</td>
<td>#{{ reservation.subject.subject_description }}</td>
<td>#{{ reservation.schedule }}</td>
<td>#{{ reservation.subject.units }}</td>
<td>#{{ reservation.room_no }}</td>
<td>
<button class="btn btn-xs btn-danger">Delete</button>
</td>
</tr>
</body>
</table>
And here's my all.js
new Vue({
el: '#app-layout',
data: {
reservations: []
},
ready: function(){
this.fetchSubjects();
},
methods:{
fetchSubjects: function(){
this.$http({
url: 'http://localhost:8000/reservation',
method: 'GET'
}).then(function (reservations){
this.$set('reservations', reservations.data);
console.log('success');
}, function (response){
console.log('failed');
});
},
addSubject: function(id,student_id){
this.$http({
url: 'http://localhost:8000/reservation',
data: { sectionSubjectId: id, studentId: student_id },
method: 'POST'
}).then(function(response) {
console.log(response);
},function (response){
console.log('failed');
});
}
}
});
Can anyone suggets me on how to solve this problem, without the need of refreshing the page.

Resources