How to write code insert multiple data to database Laravel - laravel

I want to fill and insert a lot of duplicates into the database. In the same table But i don't know how to write code on the controller. Laravel
html
<table class="table ">
<thead>
<tr>
<td width="5%"><center>ลำดับ</center></td>
<td width="20%"><center>เลขบัญชี</center></td>
<td width="40%"><center>ชื่อบัญชี</center></td>
<td width="35%"><center>จำนวนเงิน</center></td>
<td width="10%"><center></td>
</tr>
</thead>
<tbody class="resultbody">
</tbody>
</table>
Script
$(function () {
$('.add').click(function () {
var n = ($('.resultbody tr').length - 0) + 1;
var tr =
'<tr><td width="5%" class="no" name="svae_no"><center>' + n + '</center></td>' +
'<td width="20%"><input type="text" class="name form-control" name="rows[0][save_id]"></td>'+
'<td width="40%"><input type="text" class="fname form-control" name="rows[0][save_name]"></td>'+
'<td width="35%"><input type="text" class="fname form-control" name="rows[0][save_money]"></td>'+
'<td width="10%"><input type="button" class="btn btn-danger delete" value="x"></td></tr>';
$('.resultbody').append(tr);
});
$('.resultbody').delegate('.delete', 'click', function () {
$(this).parent().parent().remove();
});
});
controller add data
public function add(Request $request){$save_no = $request->input('save_no');
$save_id = $request->input('save_id');
$save_name = $request->input('save_name');
$save_money = $request->input('save_money');$data_save=array(
'mem_died_id'=>$mem_died_id,
'save_no'=>$save_no,
'save_id'=>$save_id,
'save_name'=>$save_name,
'save_money'=>$save_money);
DB::table('died_save')->insert($data_save);return back();

If we work on big project and then we maybe require to add multiple rows on database using laravel eloquent. Laravel provide insert method for bulk records create on db.
In bellow example you can see i use multidimensional $myItems array variable and that insert multiple records same time using DB::insert(). So let's see and try this.
Example:
$myItems = [
['title'=>'HD Topi','description'=>'It solution stuff'],
['title'=>'HD Topi 2','description'=>'It solution stuff 2'],
['title'=>'HD Topi 3','description'=>'It solution stuff 3']
];
DB::table("items")->insert($myItems);

Related

Cannot update multiple rows with same value in Laravel Vue Axios

can't update multiple row with a single value passing from vue js.I want to add pay value with database column advance with previous value in database.And also how to pass substraction of patientInfo.due-form.pay using axios.
Vuejs template:
<form #submit.prevent="updatePatientPayment">
<table class="table">
<tfoot>
<tr>
<td colspan="5" class="text-right">Total</td>
<td class="text-right">{{patientInfo.total}}</td>
</tr>
<tr>
<td colspan="5" class="text-right">Advance Paid</td>
<td class="text-right">{{patientInfo.advance}}</td>
</tr>
<tr>
<td colspan="5" class="text-right">Due</td>
<td class="text-right" >{{patientInfo.due}}</td>
</tr>
<tr>
<td colspan="5" class="text-right">Payable</td>
<input class="form-control text-right" type="number" v-model="form.pay"/>
</tr>
<tr>
<td colspan="5" class="text-right">New Due</td>
<td class="text-right">{{patientInfo.due-form.pay}}</td>
</tr>
</tfoot>
</table>
<b-button type="submit" variant="success">Submit</b-button>
</form>
Vuejs Script:
<script>
export default {
data(){
return{
id:this.$route.params.id,
patient:[],
patientInfo:{},
form:{
pay:0,
}
}
},
methods:{
updatePatientPayment() {
this.$http.post('http://127.0.0.1:8000/api/updatePatientPayment/' + this.id,this.form)
.then(()=>{
self.message = 'Data is entered';
})
},
}
</script>
Laravel Controller:
public function updatePatientPayment($id, Request $request)
{
$updatePatientPayment = Patient::find([$id]);
foreach($updatePatientPayment as $p){
$p->advance = $p->update([$advance + $request->pay]);
$p->save();
}
return response()->json(['successfully updated']);
}
As already mentioned you don't need an array here if you only update one Patient.
public function updatePatientPayment($id, Request $request)
{
// 1. Get the patient you want to update
// Do not wrap $id in [] if you only need to find one entity
$patient = Patient::find($id);
// 2. Change the value of the patient
// Do not use update when you assign the value to the model
$patient->advance += $request->pay;
// 3. Save the change
$patient->save();
// 4. Respond
return response()->json(['successfully updated']);
}
Alternatively, you can also use update if you want to, but be aware that your advance field must be defined as fillable to do so.
public function updatePatientPayment($id, Request $request)
{
// 1. Get the patient you want to update
// Do not wrap $id in [] if you only need to find one entity
$patient = Patient::find($id);
// 2. Update directly
$patient->update(['advance' => $patient->advance + $request->pay]);
// 3. Respond
return response()->json(['successfully updated']);
}
update will already save your change.
In your code $advance is not defined. You cannot access the existing column as you did.

Laravel and Vuejs axios delete gives no error but doesnt delete

I created a web route that must delete a contact based on a specific id and it looks like this:
Route::delete('/api/deleteContact/{id}', 'ContactController#destroy');
Then inside the controller, I have the following:
public function destroy($id)
{
// delete a contact by id
return response()->json(Contact::whereId($id), 200);
}
Inside one of my blade template files, I call the Vue component which displays the list of contacts:
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Phone</th>
</tr>
</thead>
<tbody>
<tr v-for="contact in contacts">
<td> {{ contact.id }} </td>
<td> {{ contact.name }} </td>
<td> {{ contact.phone }} </td>
<td><button class="btn btn-secondary">Edit</button></td>
<td><button #click="deleteContact(contact.id)" class="btn btn-danger">Delete</button></td>
</tr>
</tbody>
</table>
The delete button calls the deleteContact method and received the contact id in question.
The method looks like this:
deleteContact(id){
axios.delete('/api/deleteContact/' + id)
.then(res => {
for(var i = 0; i < this.contacts.length; i++) {
if(this.contacts[i].id == id) {
this.contacts.splice(i, 1);
}
}
})
.catch(err => console.log(err));
}
When I click to delete, the promise(then) occurs, however, after refreshing the page, I noticed that nothing was deleted and I see no errors in the console.
How can I successfully delete the contact based on the id passed in the deleteContact function ?
You have to append delete at the end of query like this:
public function destroy($id)
{
// delete a contact by id
return response()->json(Contact::where('id',$id)->delete(), 200);
}

How can I insert array using ajax laravel?

Help please ,I recover my data in frontend use jquery and I can display in console, now I want to insert these data in the database we are using ajax and laravel, here is my table.
Hi,help please ,I recover my data in frontend use jquery :
<table class="table table-bordered" id="mytable">
<tr>
<th>Archive</th>
<th><input type="checkbox" id="check_all"></th>
<th>S.No.</th>
<th>matricule</th>
<th>nom & prenom</th>
<th>salaire net</th>
<th>nbre de jour </th>
<th>prime</th>
</tr>
#if($salaries->count())
#foreach($salaries as $key => $salarie)
<tr id="tr_{{$salarie->id}}">
<td>archive</td>
<td><input type="checkbox" class="checkbox" data-id="{{$salarie->id}}"></td>
<td>{{ ++$key }}</td>
<td class="mat">{{ $salarie->matricule }}</td>
<td class="name">{{ $salarie->nom }} {{ $salarie->prenom }}</td>
<td class="salaireValue">{{ $salarie->salairenet }}</td>
<td ><input type="text" name="nbreJ" class="form-control" value="{{$data['nbr']}}"></td>
<td><input type="text" name="prime" class="form-control" value="0"></td>
</tr>
#endforeach
#endif
</table>
This is my code jquery which allows to recover my data
<script type="text/javascript">
$(document).ready(function () {
$('#check_all').on('click', function(e) {
if($(this).is(':checked',true))
{
$(".checkbox").prop('checked', true);
} else {
$(".checkbox").prop('checked',false);
}
});
$('.checkbox').on('click',function(){
if($('.checkbox:checked').length == $('.checkbox').length){
$('#check_all').prop('checked',true);
}else{
$('#check_all').prop('checked',false);
}
});
//get value
$('.add-all').on('click', function() {
var allChecked = $('.checkbox:checked');
for (var i = 0; i < allChecked.length; i++) {
var currentHtml = $(allChecked[i]).parent().siblings('.salaireValue')[0];
var currentHtml1 = $(allChecked[i]).parent().siblings('.name')[0];
var currentHtml2 = $(allChecked[i]).parent().siblings('.mat')[0];
var currentHtml3 = $(allChecked[i]).parent().siblings('.datea')[0];
var result = parseInt($(currentHtml)[0].innerText);
var result1 = $(currentHtml1)[0].innerText;
var result2 = parseInt($(currentHtml2)[0].innerText);
console.log(result);
console.log(result1);
console.log(result2);
}
});
});
</script>
This my controller I do not know how to write the function.
public function addMultiple(Request $request){
dd(request());
}
route
Route::post('mensuel', ['as'=>'salarie.multiple-add','uses'=>'SalarieController#addMultiple']);

laravel vue send array to backend

I want to send array of id's to backend with one button from vuejs table but i get error 500.
Logic
Check the check boxes
Collect the id's
Send id's to back-end when click on button
update the view
Code
template
<table class="table table-dark table-hover table-bordered table-striped">
<thead>
<tr>
<th class="text-center" width="50">
//the button
<button class="btn btn-outline-danger" #click="withdraw(index)">Withdraw</button>
</th>
<th class="text-center" width="50">#</th>
<th class="text-center">Amount</th>
</tr>
</thead>
<tbody>
<tr v-for="(income,index) in incomes" v-bind:key="index">
<td class="text-center">
//check box input
<input v-if="income.withdraw == '0'" type="checkbox" :id="income.id" :value="income.amount" v-model="checkedNumbers">
</td>
<td class="text-center">{{index+1}}</td>
<td class="text-center">Rp. {{formatPrice(income.amount)}}</td>
</tr>
<tr>
<td colspan="2"></td>
<td>
<span>Withdraw for today, Sum: <br> Rp. {{ formatPrice(sum) }}</span>
</td>
</tr>
</tbody>
</table>
script
export default {
data() {
return {
incomes: [],
checkedNumbers: [],
}
},
computed: {
sum() {
return this.checkedNumbers.reduce(function (a, b) {
return parseInt(a) + parseInt(b);
}, 0);
}
},
methods: {
withdraw(index) {
let checkedids = this.incomes[index]
axios.post(`/api/withdrawbutton/`+checkedids).then(response => {
this.income[index].withdraw = '1'
this.$forceUpdate()
});
}
}
}
route
Route::post('withdrawbutton/{id}', 'IncomeController#withdrawbutton');
controller
public function withdrawbutton($id)
{
$dowithdraw = Income::where('id', $id)->get();
$dowithdraw->withdraw = '1';
$dowithdraw->save();
return response()->json($dowithdraw,200);
}
Any idea where is my mistake and how to fix it?
......................................................................................................................
Don't send the list as a GET parameter, send it as a POST:
let params = {}
params.ids = this.checkedNumbers
axios.post(`/api/withdrawbutton/`, params)
.then(response => {
this.income[index].withdraw = '1'
this.$forceUpdate()
});
Controller
public function withdrawbutton(Request $request)
{
$dowithdraws = Income::whereIn('id', $request->input('ids', []));
$dowithdraws->update(['withdraw' => '1']);
return response()->json($dowithdraws->get(), 200);
}
Route
Route::post('withdrawbutton/', 'IncomeController#withdrawbutton');
And I don't think you need to update anything in the front because you already have them checked (if you want to keep them checked)

Ajax call not working on datatables pages,except first page

i am using datatables.And on the table there is button on each row.
When I click on the trash button,ajax works only for the first 10 row.
But when I move on to next pages it does not work anymore.
Here is my table code:
<script type="text/javascript" language="javascript" src="//cdn.datatables.net/plug-ins/725b2a2115b/integration/bootstrap/3/dataTables.bootstrap.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#example').dataTable();
} );
</script>
<table id="example" class="table table-bordered">
<thead>
<tr>
<th class="success">Id</th>
<th class="success">Image</th>
<th class="success">Title</th>
<th class="success">Action</th>
</tr>
</thead>
<tbody>
<?php
$query = mysqli_query($connect,"SELECT * FROM movie");
while ($result = mysqli_fetch_row($query)){
echo'
<tr>
<td>'.$result[0].'</td>
<td><img class="img-responsive" style="max-height:50px;" src="'.$result[5].'"></td>
<td>'.$result[1].'</td>
<td>
<div class="btn-group" data-toggle="buttons">
<label id="remID" class="btn btn-sm btn-default">
<span class="text-danger glyphicon glyphicon-trash"></span>
</label>
<label class="btn btn-sm btn-default">
<span class="text-primary glyphicon glyphicon-edit"></span>
</label>
</div>
</td>
</tr>
';
echo'
<script>
$(document).ready(function(){
$("#remID").click(function(){
$.post("remMovie.php",
{
id:"'.$result[0].'"
},
function(data,status){
alert(status);
});
});
});
</script>
';
}
?>
</tbody>
</table>
Here is my PHP part of ajax action:
<?php
include('adminchk.php');
include('config.php');
$movieID = $_POST['id'];
$query = mysqli_query($connect,"DELETE from movie where id='$movieID'");
if ($query){
echo"movie deleted";
}
else {
echo"ERROR!";
}
?>
I dont know why this is happening.I want the trash button to work for every row of datatable.
To execute any Code after the Data Table has been paginated (basically redrawn), you need to add fnDrawCallback function inside .dataTabale() method. All codes written inside the Callback function will work after the table has been redrawn. Here is an example...
$(document).ready( function() {
$('#example').dataTable({
"fnDrawCallback": function( oSettings ) {
// Write any code (also ajax code that you want to execute)
// that you want to be executed after
// the table has been redrawn
}
});
});
You should try something like fnDrawCallback event.
Here is the doc : http://legacy.datatables.net/usage/callbacks#fnDrawCallback
When the datable change, you bind the buttons with the function you want.
JS :
$(document).ready( function() {
$('#example').dataTable( {
"fnDrawCallback": function( oSettings ) {
alert( 'DataTables has redrawn the table' );
}
} );
} );

Resources