Cart with login in laravel 5.7 - laravel

I am implement shopping cart with login & witout login i am using cart package from laravel but it will stored cart item on local storage now i want to login and add cart item in database. When i am not login then item adds in local storage but when i am login then items add in database i am confuse. how i am implement I am sharing my code that i am developed need solutions
Controller:
public function add_to_cart(Request $req)
{
$userId=Session::get('userid');
$qty=$req->qty;
$product_id=$req->product_id;
$product_info=DB::table('product_details')
->join('subcategory','subcategory.sub_id','=','product_details.sub_id')
->select('subcategory.image','subcategory.name_of_subcategory','product_details.*')
->where('product_details.product_id',$product_id)->first();
$sub_id=$product_info->sub_id;
//dd($product_info);
Cart::add(array(
'id'=>$product_info->product_id,
'name'=>$product_info->name_of_subcategory,
'price'=>$product_info->price,
'qty'=>$qty,
'options'=>array('image' =>$product_info->image,'description'=>$product_info->description_of_product)
));
if($userId)
{
$content=\Cart::Content();
}
// $content=\Cart::Content();
// dd($content);
//$data = DB::select('select * from product_details where sub_id = ?',[$sub_id]);
//return view('productdetails',['data'=>$data]);
return view('cart');
}
blade
#extends('layout.header')
#section('content')
<?php
$contents=\Cart::Content();
?>
<div class="container mt-5">
<table id="cart" class="table table-hover table-condensed">
<thead>
<tr>
<th>Product</th>
<th>Price</th>
<th>Quantity</th>
<th class="text-center">Subtotal</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach($contents as $v_contents)
<tr>
<td data-th="Product">
<div class="row">
<div class="col-sm-4 hidden-xs"><img src="{{asset('images/'.$v_contents->options->image)}}" alt="..." class="img-responsive"/ height="100" width="100"></div>
<div class="col-sm-8">
<h4 class="nomargin">{{$v_contents->name}}</h4>
<p>{{$v_contents->options->description}}</p>
</div>
</div>
</td>
<td data-th="Price">{{$v_contents->price}}</td>
<td data-th="Quantity">
<div class="plus-minus" style="width:150px; ">
<div class="input-group">
<span class="input-group-btn">
<button type="button" class="btn btn-default btn-number" id="subs" >
<span class="fa fa-minus"></span>
</button>
</span>
<input type="text" id="qty" name="qty" class="form-control input-number" value="{{$v_contents->qty}}" min="1" max="10">
<span class="input-group-btn">
<button type="button" class="btn btn-default btn-number" data-type="plus" id="adds">
<span class="fa fa-plus"></span>
</button>
</span>
</div>
<input type="hidden" name="product_id" id="product_id" value="{{ $v_contents->rowId}}">
</div>
</td>
<td data-th="Subtotal" class="text-center">{{ $v_contents->total}}</td>
<td class="actions" data-th="">
<a class="btn btn-danger btn-sm" href="{{ URL::to('/delete-to-cart/'.$v_contents->rowId)}}"><i class="fa fa-trash-o"></i></a>
</td>
</tr>
#endforeach
</tbody>
<tfoot>
<!-- <tr class="visible-xs">
<td class="text-center"><strong>Total 1.99</strong></td>
</tr> -->
<tr>
<td><i class="fa fa-angle-left"></i> Continue Shopping</td>
<td colspan="2" class="hidden-xs"></td>
<td class="hidden-xs text-center"><strong>Total {{\Cart::subtotal()}}</strong></td>
<td>Checkout <i class="fa fa-angle-right"></i></td>
</tr>
</tfoot>
</table>
</div>
<script type="text/javascript">
/*$('#adds').click(function add() {
var $qty = $("#qty");
var a = $qty.val();
a++;
$("#subs").prop("disabled", !a);
$qty.val(a);
});
$("#subs").prop("disabled", !$("#qty").val());
$('#subs').click(function subst() {
var $qty = $("#qty");
var b = $qty.val();
if (b >= 1) {
b--;
$qty.val(b);
}
else {
$("#subs").prop("disabled", true);
}
});*/
</script>
<script>
$(document).ready(function(){
$(document).on('click', '#adds', function(e) {
var qty = $('#qty').val();
var product_id=$('#product_id').val();
//alert(qty);
e.preventDefault()
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
jQuery.ajax({
url: "{{ url('/increment') }}",
method: 'get',
data: {
qty: qty,id:product_id
},
success: function(result){
jQuery('#qty').val(result.qty);
}});
});
});
</script>
<script>
$(document).ready(function(){
$(document).on('click', '#subs', function(e) {
var qty = $('#qty').val();
var product_id=$('#product_id').val();
//alert(qty);
e.preventDefault()
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
jQuery.ajax({
url: "{{ url('/decrement') }}",
method: 'get',
data: {
qty: qty,id:product_id
},
success: function(result){
jQuery('#qty').val(result.qty);
}});
});
});
</script>
#endsection

Related

Datatables - Search Box outside datatable (Laravel/Vue .js)

I am using Datatables in my application (Bookstore created in laravel/vuejs) and I would like my search box to be outside of the table. the problem which I am facing is that the search box is not searching the data until I refresh/reload the page 1 or 2 times.
any kind of help will be highly appreciated.
Javascript code is below
$(document).ready(function() {
var tables = $("#datatable-fixed-header30").DataTable({
paging: false,
dom: "t"
});
// $(".dataTables_filter").hide();
$("#bookSearch").keyup(function() {
tables.search($(this).val()).draw();
});
});
Full Code in the vue page is like below
<template>
<div class="container">
<div class="col-md-12 col-sm-12 col-xs-12" v-for="User1 in Users.data" v-bind:key="User1.id">
<div class="x_panel" v-if="User1.type=='admin'">
<div class="x_content">
<div
id="datatable-buttons_wrapper"
class="dataTables_wrapper form-inline dt-bootstrap no-footer"
>
<div class="dt-buttons btn-group">
<button
class="btn btn-success buttons-copy buttons-html5 btn-sm"
tabindex="0"
aria-controls="datatable-buttons"
#click="newModal"
>ثبت کاربرد جدید</button>
</div>
<!-- /.row -->
<div class="row">
<div class="col-lg-6" style="margin-top:-31px;float:left;margin-left:-213px;">
<div class="input-group">
<span class="input-group-btn">
<button class="btn btn-info btn-flat" type="button">
<i class="fa fa-search"></i>
</button>
</span>
<input type="text" class="form-control" id="bookSearch" placeholder="لټون..." />
</div>
<!-- /input-group -->
</div>
<div class="col-sm-12">
<table
id="datatable-fixed-header30"
class="table table-striped table-bordered dataTable no-footer"
role="grid"
aria-describedby="datatable-fixed-header_info"
>
<thead>
<tr role="row">
<th style="width:1%">
<input type="checkbox" #click="selectAll" v-model="allSelected" />
</th>
<th
class="sorting"
tabindex="0"
aria-controls="datatable-buttons"
rowspan="1"
colspan="1"
aria-label="کود: activate to sort column ascending"
>کود</th>
<th
class="sorting_asc"
tabindex="0"
aria-controls="datatable-buttons"
rowspan="1"
colspan="1"
aria-sort="ascending"
aria-label="نام: activate to sort column descending"
>نام</th>
<th
class="sorting"
tabindex="0"
aria-controls="datatable-buttons"
rowspan="1"
colspan="1"
aria-label=" آدرس الکترونکی: activate to sort column ascending"
>آدرس الکترونکی</th>
<th
class="sorting"
tabindex="0"
aria-controls="datatable-buttons"
rowspan="1"
colspan="1"
aria-label=" : activate to sort column ascending"
>نوعیت کاربرد</th>
<th
class="sorting"
tabindex="0"
aria-controls="datatable-buttons"
rowspan="1"
colspan="1"
aria-label=" : activate to sort column ascending"
>تاریخ ورود</th>
<th
class="sorting"
tabindex="0"
aria-controls="datatable-buttons"
rowspan="1"
colspan="1"
aria-label=" تنظیمات : activate to sort column ascending"
>تنظیمات</th>
</tr>
</thead>
<tbody>
<tr
role="row"
class="odd"
v-if="Users.data!=undefined && Users.data.length == 0 || Users.data!=undefined && Users.data.length=='' "
>
<td colspan="7" align="center" :v-show="hidebutton=false">
<p class="text-center alert alert-danger">هیڅ مورد نشته</p>
</td>
</tr>
<tr
role="row"
class="even"
v-else
v-show="hidebutton=true"
v-for="User in Users.data"
v-bind:key="User.id"
>
<td>
<div class="custom-control custom-checkbox">
<input
class="form-check-input"
type="checkbox"
:value="User.id"
v-model="checkedRows"
id="chekboxs"
/>
<label class="form-check-label"></label>
</div>
</td>
<td>{{User.id}}</td>
<td>{{User.name}}</td>
<td>{{User.email}}</td>
<td>
<span class="tag tag-success">{{User.type}}</span>
</td>
<td>{{User.created_at|mydate}}</td>
<td>
<a href="#" class="btn btn-info btn-xs" #click="editModal(User)">
<i class="fa fa-pencil"></i> ویرایش
</a>
<a
v-if="User.type !='admin'"
href="#"
class="btn btn-danger btn-xs"
#click="deleteUser(User.id)"
>
<i class="fa fa-trash-o"></i> حذف
</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="card-footer">
<pagination :data="Users" #pagination-change-page="getResults"></pagination>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
components: {
},
data() {
return {
color: "#59c7f9",
isLoading: false,
fullPage: true,
hidebutton: true,
color: "blue",
editMode: false,
Users: {},
selected: [],
allSelected: false,
checkedRows: [],
data: [],
url: "api/getAllusers",
// selectAll: false,
form: new Form({
id: "",
name: "",
email: "",
password: "",
type: "",
bio: "",
photo: ""
})
};
},
computed: {},
methods: {
selectAll: function() {
this.checkedRows = [];
if (!this.allSelected) {
for (user in this.data) {
this.checkedRows.push(this.data[user].id);
}
}
},
doAjax() {
this.isLoading = true;
this.color = "blue";
// simulate AJAX
setTimeout(() => {
this.isLoading = false;
}, 1000);
},
onCancel() {
console.log("User cancelled the loader.");
},
refrash: function() {
$("#addNew").modal("hide");
},
loadallUsers() {
axios.get("api/user").then(({ data }) => (this.Users = data));
},
getResults(page = 1) {
this.isLoading = true;
this.color = "blue";
// simulate AJAX
setTimeout(() => {
this.isLoading = false;
}, 500);
axios
.get("api/user?page=" + page)
.then(response => {
this.Users = response.data;
})
.then(
function(response) {
this.Users = response.data.data;
}.bind(this)
);
},
loadUsers() {
if (this.$gate.isAdmin()) {
this.$Progress.start();
axios.get("api/user").then(({ data }) => (this.Users = data));
axios.get("api/getAllusers").then(({ data }) => (this.data = data));
this.$Progress.finish();
}
},
createUser() {
if (this.form.name == "") {
toast.fire({
type: "warning",
icon: "warning",
html: "<h5>نام لازم است.</h5>"
});
} else if (this.form.email == "") {
toast.fire({
type: "warning",
icon: "warning",
html: "<h5> آدرس الکترونکی لازم است.</h5>"
});
} else if (this.form.password == "") {
toast.fire({
type: "warning",
icon: "warning",
html: "<h5> رمز لازم است.</h5>"
});
} else if (this.form.type == "") {
toast.fire({
type: "warning",
icon: "warning",
html: "<h5> نوعیت کاربردد لازم است.</h5>"
});
} else {
this.form
.post("api/user")
.then(() => {
// the below function will be use to reload the page
// this.$emit("refreshPage");
$("#addNew").modal("hide");
toast.fire({
icon: "success",
type: "success",
html: "<h5> کاربردد موافقانه اجاد گردید</h5>"
});
Fire.$emit("refreshPage");
this.form.reset();
// this.$Progress.finish();
})
.catch(er => {
console.log(er);
});
}
}
},
created() {
this.loadUsers();
// load the page after 3 secound
Fire.$on("refreshPage", () => {
this.loadUsers();
});
}
};
$(document).ready(function() {
var tables = $("#datatable-fixed-header30").DataTable({
paging: false,
dom: "t"
});
// $(".dataTables_filter").hide();
$("#bookSearch").keyup(function() {
tables.search($(this).val()).draw();
});
});
</script>
The following approach will allow you to use a search box outside of the table. You should be able to adapt this to your specific code.
My data is in a table called "animals":
<table id="animals" class="display dataTable cell-border" style="width:100%">
...
</table>
1) Set up the search field:
<div id="external_filter" class="dataTables_filter" style="margin: 20px 0;">
<label>External Search:
<input id="external_search" type="search" class="" placeholder="" aria-controls="animals">
</label>
</div>
In this example, I use the same class (dataTables_filter) as the original filter box - you can use whatever you want.
2) Define a basic DataTable:
This is the minimum definition needed to show the technique - you can add all your extra controls, as you need:
$(document).ready(function() {
var table = $('#animals').DataTable({
"initComplete": function(settings, json) {
$('#animals_filter').remove();
}
});
$('#external_filter input').off().keyup(function () {
table.search(this.value).draw();
});
});
The initComplete function is used to hide the original search box. We want searching to still be enabled, so we can't use "searching": false.
The $('#external_filter input') code handles searching for you. The data you enter into the search box is captured by this.value and is passed to the table's search functionality.
The web page looks like this:
The overall code is as follows:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>External Search Box</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">
</head>
<body>
<div style="margin: 20px;">
<div id="external_filter" class="dataTables_filter" style="margin: 20px 0;">
<label>External Search:
<input id="external_search" type="search" class="" placeholder="" aria-controls="animals">
</label>
</div>
<table id="animals" class="display dataTable cell-border" style="width:100%">
<thead>
<tr><th>Animal</th><th>Collective Noun</th><th>Language</th></tr>
</thead>
<tbody>
<tr><td>antelopes</td><td>herd</td><td>English</td></tr>
<tr><td>elephants</td><td>herd</td><td>English</td></tr>
<tr><td>éléphants</td><td>troupeau</td><td>French</td></tr>
<tr><td>Hounds</td><td>pack</td><td>English</td></tr>
<tr><td>kittens</td><td>kindle</td><td>English</td></tr>
<tr><td>lions</td><td>pride</td><td>English</td></tr>
<tr><td>pingouins</td><td>colonie</td><td>French</td></tr>
<tr><td>ravens</td><td>unkindness</td><td>English</td></tr>
<tr><td>whales</td><td>pod</td><td>English</td></tr>
<tr><td>zebras</td><td>herd</td><td>English</td></tr>
</tbody>
</table>
</div>
<script type="text/javascript">
$(document).ready(function() {
var table = $('#animals').DataTable({
"initComplete": function(settings, json) {
$('#animals_filter').remove();
}
});
$('#external_filter input').off().keyup(function () {
table.search(this.value).draw();
});
});
</script>
</body>
</html>

i try to mount a component in a component vue

i i try to mount a component in a component, this component its a partial, in especifict its a paginator, which i need to integrate, i use props in the paginate component.
but i have a problem, in the console appears the next messagge "Failed to mount component: template or render function not defined." i am new in vue js, i using router-view i don´t know if this
it is affecting en the problem the code its the next :
Pedido.vue
<template>
<div id="pedido" style="margin-top:50px">
<div class="row justify-content-center">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h4 class="card-title">Pedidos</h4>
<div class="card-tools" style="position: absolute;right: 1rem;top: .5rem;">
<button type="button" class="btn btn-info" >
Nuevo
<i class="fas fa-plus"></i>
</button>
<button type="button" class="btn btn-primary" >
Recargar
<i class="fas fa-sync"></i>
</button>
</div>
</div>
<div class="card-body">
<div class="mb-3">
<div class="row">
<div class="col-md-2">
<strong>Buscar por :</strong>
</div>
<div class="col-md-3">
<select class="form-control" id="fileds">
<option value="total">Codigo</option>
<option value="name">Nombre</option>
<option value="email">Apellido</option>
<option value="phone">Telefono</option>
<option value="address">Direccion</option>
</select>
</div>
<div class="col-md-7">
<input type="text" class="form-control" placeholder="Buscar">
</div>
</div>
</div>
<div class="table-responsive">
<table class="table table-hover table-bordered table-striped">
<thead>
<tr>
<th scope="col">Codigo</th>
<th scope="col">Nombre</th>
<th scope="col">Apellido</th>
<th scope="col">Telefono</th>
<th scope="col">Rut</th>
<th scope="col" class="text-center">Action</th>
</tr>
</thead>
<tbody>
<tr v-for="(pedido, index) in pedidos" :key="pedido.codigo">
<th scope="row">{{ index + 1}}</th>
<td>{{ pedido.nombre_cliente}}</td>
<td>{{ pedido.apellido_cliente }}</td>
<td>{{ pedido.telefono_cliente}}</td>
<td>{{ pedido.rut_cliente }}</td>
<td class="text-center">
<button type="button" class="btn btn-info btn-sm">
<i class="fas fa-eye"></i>
</button>
<button type="button" class="btn btn-primary btn-sm">
<i class="fas fa-edit"></i>
</button>
<button
type="button"
class="btn btn-danger btn-sm"
>
<i class="fas fa-trash-alt"></i>
</button>
</td>
</tr>
<tr >
<td colspan="6">
<div class="alert alert-danger" role="alert">No se ah encontrado resultados :(</div>
</td>
</tr>
</tbody>
</table>
<div class="card-footer">
<pagination
v-if="pagination.last_page > 1"
:pagination="pagination"
:offset="5"
#paginate="getData()"
></pagination>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data(){
return{
pedidos:[],
pagination: {
current_page: 1,
},
}
},
mounted() {
console.log('Component mounted.')
this.getData();
},
methods:{
getData(){
this.$Progress.start();
axios.get("api/pedidos?page=" + this.pagination.current_page)
.then(response =>{
this.pedidos = response.data.data;
this.pagination = response.data.meta;
this.$Progress.finish();
})
.catch(e =>{
console.log(e)
this.$Progress.fail();
})
//.then(({ data }) => (this.pedidos = data));
}
},
}
</script>
this its PaginationComponent.vue:
<template>
<nav aria-label="...">
<ul class="pagination justify-content-center">
<li class="page-item" :class="{ disabled: pagination.current_page <= 1 }">
<a class="page-link" #click.prevent="changePage(1)" >First page</a>
</li>
<li class="page-item" :class="{ disabled: pagination.current_page <= 1 }">
<a class="page-link" #click.prevent="changePage(pagination.current_page - 1)">Previous</a>
</li>
<li class="page-item" v-for="page in pages" :key="page" :class="isCurrentPage(page) ? 'active' : ''">
<a class="page-link" #click.prevent="changePage(page)">{{ page }}
<span v-if="isCurrentPage(page)" class="sr-only">(current)</span>
</a>
</li>
<li class="page-item" :class="{ disabled: pagination.current_page >= pagination.last_page }">
<a class="page-link" #click.prevent="changePage(pagination.current_page + 1)">Next</a>
</li>
<li class="page-item" :class="{ disabled: pagination.current_page >= pagination.last_page }">
<a class="page-link" #click.prevent="changePage(pagination.last_page)">Last page</a>
</li>
</ul>
</nav>
</template>
<script>
export default {
props:['pagination', 'offset'],
methods: {
isCurrentPage(page){
return this.pagination.current_page === page
},
changePage(page) {
if (page > this.pagination.last_page) {
page = this.pagination.last_page;
}
this.pagination.current_page = page;
this.$emit('paginate');
}
},
computed: {
pages() {
let pages = []
let from = this.pagination.current_page - Math.floor(this.offset / 2)
if (from < 1) {
from = 1
}
let to = from + this.offset -1
if (to > this.pagination.last_page) {
to = this.pagination.last_page
}
while (from <= to) {
pages.push(from)
from++
}
return pages
}
}
}
</script>
app.js
Vue.component('pagination', require('./components/partial/PaginationComponent.vue'));
const app = new Vue({
el: '#app',
router
});
this its the error
but in the extension of vue in the console i see the
properties of the object, this is fine,
but I do not know what I'm doing wrong, like I said I'm new to this.
extension of vue
I hope they understand me,
I would greatly appreciate your help.
Pedido.vue
export default {
components: { pagination },
data(){ ....
maybe is this problem
On the file app.js you apart from especify where you are mounting your component (in this case on the div with id "app"), you also need to tell Vue what to render.
Your component on the app.js file should include a template or a render function, that's why you are getting the error "Failed to mount component: template or render function not defined.
You can add it like this:
const app = new Vue({
el: '#app',
router,
template: '<pagination/>'
});
Or using the render function like this:
import Pagination from './components/partial/PaginationComponent.vue'
const app = new Vue({
el: '#app',
router,
render: (h) => h(Pagination)
});
well, i tried with their answer, but dont worked ,
I managed to solve it by adding:
Vue.component('pagination', require('./components/partial/PaginationComponent.vue').default);

insert multiple laravel checkbox datatable

I want to insert multi rows checked in my data table, when I click a button valider, everyone I have a problem in a laravel framework, I want to insert line check in a data table when click on button validate, this my code
the display of the salary list
<body>
<div class="container" id="app">
<div class="list-group">
<div class="list-group-item">
<h3>Pointage Mensuel</h3>
<div class="col-md-6 col-md-offset-3">
<h3>jour : {{$data['datek']}} chantier : {{$data['chantier_name']}}</h3>
</div>
<button class="btn btn-success add-all" data-url="">Valider Pointage de mois</button>
</div>
</div>
<div class="list-group">
<div class="list-group-item">
<table class="table table-bordered">
<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>{{ $salarie->matricule }}</td>
<td>{{ $salarie->nom }} {{ $salarie->prenom }}</td>
<td>{{ $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>
</div>
</div>
<!-------------------//////////////////////////------------->
</div>
</body>
code ajax for checked all /uncheck and
<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); }});
$('.add-all').on('click', function(e) {
var idsArr = [];
$(".checkbox:checked").each(function() {
idsArr.push($(this).attr('data-id'));});
if(idsArr.length <=0) {
alert("Please select atleast one record to pointer.");
} else {
var strIds = idsArr.join(",");
$.ajax({
url: "{{ route('salarie.multiple-add') }}",
type: 'POST',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: {
'ids' : strIds},
success: function (data) {
if (data['status']==true) {
$(".checkbox:checked").each(function() {
alert(strIds); });
alert(data['message']);
} else {
alert('Whoops Something went wrong!!');}
window.location.reload()},
error: function (data) {
alert(data.responseText);}});} }); });
</script>
function controller addMultiple
public function addMultiple(Request $request){
$pointage=new Pointage();
$pointage->datep=$request->datep;
$pointage->nbrj=$request->nbrj;
$pointage->prime=$request->prime;
$pointage->solde=$request->solde;
return response()->json(['status'=>true]);
}
Apologies for late answer laptop died on me while i was busy but one way you could do it is by using array names for example:
<td><input type="checkbox" class="checkbox" name="row[$key][salarie]" data-id="{{$salarie->id}}"></td>
baiclly if you have multiple of these inputs with the same group it will make an array of inputs on your backend which you can loop through. to test this dd(request()); in your controller function above everything else. then you should be able to see what it returns in your console.
foreach(request(inputgroup) as $value){
Pointage::create([
'some_column' => $value['actualInputName']
]);
}
Update your function to something like this:
public function addMultiple(Request $request){
dd(request());
$pointage=new Pointage();
foreach(request('row') as $row){
// this is the important line $row is your request and ['salari'] is the name of the input
$pointage->salarie = $row['salarie'];
$pointage->save();
}
return response()->json(['status'=>true]);
}

Fetch Records in Angular datatable

Im new to Angular and My Requirement is
A component includes a form with the field name call "Brand" and a button to add the same record to database through angular service and there should be a datatable which is fetching all brand data from database to data table.
so by using fetchall method in ts file, i am assigning values to data table. im calling fetchall method to ngoninit() which helps me to show the data in table while component get initialized. to add record, i am using a method call addyear() and calling the same method to onSumbit(). my problem is when i add the record to database, i should be able to load newly added record to angular data table! since that method in ngoninit(), i have to refresh the browser to get the record in data table kindly give me a solution. for the back end, im using Spring boot with Postgres database
My Component TS file
constructor(private brandService:BrandService,private toastyService: ToastyService) { }
ngOnInit() {
this.findbrand();
}
onSubmit()
{
this.saveBrand();
this.submitted=true;
}
saveBrand()
{
this.brandService.addbrand(this.brand).subscribe
(data=>this.addToast({title:'Record Has been added Successfully', msg:'', timeout: 5000, theme:'default', position:'top-right', type:'success'}),
error=>this.addToast({title:'Record Not Added! Sorry', msg:'', timeout: 5000, theme:'default', position:'top-right', type:'error'}));
this.brand=new Brand();
}
findbrand()
{
this.brandService.findbrand().subscribe(data=>this.data=data,error=>this.addToast({title:'Record Cannot be found! Sorry', msg:'', timeout: 5000, theme:'default', position:'top-right', type:'error'}));
}
My Service.TS file
export class BrandService {
constructor(private http:HttpClient) { }
private baseUrl='http://localhost:8080/snazzy-engine/brand';
addbrand(brand:object):Observable<any>
{
return this.http.post(`${this.baseUrl}` + `/insert`, brand,{
headers: {'schemaName':'test.'}
});
}
findbrand():Observable<any>
{
return this.http.get(`${this.baseUrl}` + `/find-all`,{
headers: {'schemaName':'test.'}
});
}
getbrandid(id: number): Observable<Object> {
return this.http.get(`${this.baseUrl}/find-one/${id}`, {headers:
{'schemaName':'test.'}});
}
}
My HTML File
<div class="table-content crm-table">
<div class="project-table">
<div id="crm-contact" class="dt-responsive">
<div class="row">
<div class="col-xs-12 col-sm-12 col-sm-12 col-md-6">
<div>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-6">
<div style="text-align: right;">
<label>Search:
<input type="search" [(ngModel)]="filterQuery" class="form-control input-sm full-data-search" placeholder="Search name">
</label>
</div>
</div>
</div>
<!-- <div class="panel-heading">User information</div>-->
<div class="table-responsive">
<table class="table table-bordered table-hover table-sm" [mfData]="data | dataFilter : filterQuery" #mf="mfDataTable" [mfRowsOnPage]="rowsOnPage" [(mfSortBy)]="sortBy"
[(mfSortOrder)]="sortOrder">
<thead class="thead-dark text-center">
<tr>
<th style="width:10%">
<mfDefaultSorter by="brandId">Brand ID</mfDefaultSorter>
</th>
<th style="width:70%">
<mfDefaultSorter by="name">Brand Name</mfDefaultSorter>
</th>
<th style="width:10%">
<mfDefaultSorter by="more">More</mfDefaultSorter>
</th>
<th style="width:10%">
<mfDefaultSorter by="checkbox">Delete</mfDefaultSorter>
</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of mf.data; let i = index;">
<td>{{item.brandId}}</td>
<td>{{item.brand}}</td>
<td class="action-icon">
<button type="button" class="btn btn-sm btn-primary" (click)="findybrandid(item.brandId);modalDefault.show();">
edit
</button>
</td>
<td>
<div class="checkbox text-center">
<label><input type="checkbox" value=""></label>
</div>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="10">
<mfBootstrapPaginator class="pagination-main f-right"></mfBootstrapPaginator>
</td>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
<div style="text-align:center;">
<button class="btn btn-out btn-danger ripple light"><i class="icofont icofont-check-circled"></i>Delete</button>
</div>
</div>
</div>
</div>
try this
saveBrand()
{
this.brandService.addbrand(this.brand)
.subscribe(
data => this.addToast(
{
title:'Record Has been added Successfully',
msg:'',
timeout: 5000,
theme:'default',
position:'top-right',
type:'success'
}),
error => this.addToast(
{
title:'Record Not Added! Sorry',
msg:'',
timeout: 5000,
theme:'default',
position:'top-right',
type:'error'
})
);
this.data.push(this.brand); /*change: push new data into an array*/
this.brand=new Brand();
}

knockoutjs refresh or update

I trying create a ajax-refresh shopping-cart panel. My shopping-cart is listed but I can't refresh it in $.getJSON callback function. my view and code is;
<div class="panel panel-info">
<div class="panel-heading">
<i class="fa fa-list-ul"></i> Sipariş Listeniz
</div>
<div class="panel-body">
<div id="cart" data-bind="foreach: Currencies">
<div class="">
<span data-bind="text: Currency"></span>
<table class=" table table-striped" data-bind="foreach: Items">
<tr>
<td data-bind="text: Code"></td>
<td data-bind="text: Amount"></td>
<td data-bind="text: Price"></td>
<td data-bind="text: LineTotal"></td>
</tr>
</table>
</div>
</div>
</div>
<div class="panel-footer">
</div>
</div>
and
var cartViewModel = {
Currencies: ko.observableArray()
};
$(function () {
ShowCart();
});
function AddToCart(i, a) {
$.getJSON('#Url.Action("AddToCart", "Products")/' + i + '?Amount=' + a, null, function (d) {
if (d)
ShowCart();
});
}
function ShowCart() {
$.getJSON('#Url.Action("GetCart","Products")', null, function (c) {
cartViewModel.Currencies = ko.observableArray(c);
cartViewModel.Currencies.valueHasMutated();
ko.applyBindings(cartViewModel);
});
}
How can I refresh the binding in the $.getJSON callback?
I think your problem is that you're overwriting the observables in your view-model.
All you need to do is pass a new value into the existing observable.
Try this instead:
function ShowCart() {
$.getJSON('#Url.Action("GetCart","Products")', null, function (c) {
cartViewModel.Currencies(c);
});
}

Resources