Vue Laravel Dynamic Dependent Dropdown - laravel

I am trying to get the Decoration types according to the house area types. I got the house area types but failed to get the decoration types. In Vue dev tool the "houseTypes" are showing an array but the "decorTypes" are showing "Reactive". I am also dynamically creating rows and removing them. for that i took an array
my vue file is--
<template>
<div v-for="(tab,k) in tabs" :key="k" >
<table class="table table-borderless col-md-12">
<thead>
<th>HouseAreaType</th>
<th>DecorationType</th>
<th>Action</th>
</thead>
<tbody>
<td>
<select
v-model="tab.selectedHouseType"
class="form-control select2"
id="houseType1"
required
name="houseAreaTypeId"
>
<option
v-for="houseType in houseTypes"
:key="houseType.id"
:value="houseType.id"
>
{{ houseType.name }}
</option>
</select>
</td>
<td>
<select
v-model="selectedDecor"
#change="getDescription()"
class="form-control select2"
required
>
<option
selected
v-for="decorType in decorTypes"
:key="decorType.id"
:value="decorType.id"
>
{{ decorType.name }}
</option>
</select>
</td>
<input type="submit" class="btn btn-success" value="Save" />
</td>
<td>
<input
type="button"
class="btn btn-success"
value="Add More"
#click="addRow"
/>
</td>
<td >
<input
type="button"
class="btn btn-danger"
value="Remove"
#click="removeRow(k,tab)"
/>
</td>
</tbody>
</table>
</div>
</template>
<script type="module">
export default {
data() {
return {
tabs: [{
rate:"",
selectedHouseType: "",
selectedDecor: "",
}],
tabCounter: 0,
houseTypes: {},
decorTypes: {},
};
},
methods: {
getHouseTypes() {
axios.get("/api/houseTypes").then((response) => {
this.houseTypes = response.data;
// this.productForm.colors = response.data;
});
},
addRow() {
this.tabs.push(this.tabCounter++);
},
removeRow(index,tab) {
var idx = this.tabs.indexOf(tab);
console.log(idx, index);
this.tabs.splice(idx, 1);
},
},
watch: {
'tab.selectedHouseType': function (value){
axios.get('/api/decorTypes?houseAreaTypeId=' + value)
.then((response) => {
console.log(response.data);
this.decorTypes = response.data.data;
});
},
},
mounted() {
this.getHouseTypes();
},
};
</script>
my api.php---
Route::get('/houseTypes',[CartController::class,'getHouseTypes'])->name('houseTypes');
Route::get('/decorTypes',[CartController::class,'getDecorTypes'])->name('decorTypes');
my CartController--
public function getHouseTypes()
{
$houseTypes = HouseAreaType::all();
return response()->json($houseTypes);
}
public function getDecorTypes()
{
$houseAreaTypeId = request('houseAreaTypeId');
$decorTypes = DecorationType::where('houseAreaTypeId',$houseAreaTypeId)->get();
return response()->json($decorTypes);
}

solved iy.
created a method getDecor()..
<select
v-model="tab.selectedHouseType"
#change="getDecor()"
class="form-control select2"
id="houseType1"
required
name="houseAreaTypeId"
>
in the mthods--
getDecor(){
axios.get('/api/decorTypes', {
params: {
houseAreaTypeId: this.tabs[this.tabs.length-
1].selectedHouseType
}
}).then(function(response){
console.log(response.data);
}.bind(this));
}

Related

Saving multiple data from dynamic form in Laravel and Vue JS

I have a dynamic form that successfully adds multiple rows by clicking on the add button. the problem is when I try to save data into the database it throws the below error.
{message: "Illegal string offset 'supplier_id'", exception:
"ErrorException",…} exception: "ErrorException" file:
"C:\xampp\htdocs\Bookstore\app\Http\Controllers\API\PurchaseController.php"
line: 87 message: "Illegal string offset 'supplier_id'" trace: [{file:
"C:\xampp\htdocs\Bookstore\app\Http\Controllers\API\PurchaseController.php",
line: 87,…},…]
and help will be highly appreciated
Code in the controller
public function store(Request $request)
{
$products = json_decode($request->getContent('myArray') , true);
foreach( $products as $product )
{
Purchase::create([
'supplier_id' => $product['supplier_id'],
'date' => $product['date'],
'totalAmount' => $product['totalAmount'],
'description' => $product['description']
]);
}
// return dd($myArray);
return response()->json($Purchase);
}
Form in the Purchases Vue
<form
#submit.prevent="
editMode ? updatePurchase() : createPurchase()
"
>
<div class="modal-body">
<div class="form-horizontal">
<tr v-for="(invoice_product, k) in invoice_products" :key="k">
<td scope="row" class="trashIconContainer">
<i class="fa fa-trash" #click="deleteRow(k, invoice_product)"></i>
</td>
<td style="width: 20%;">
<select
name="supplier_id[]"
id="supplier_id"
:class="{
'is-invalid': form.errors.has(
'supplier_id'
)
}"
class="form-control"
v-model="invoice_product.supplier_id"
data-live-search="true"
>
<option value selected>د پلورونکي ټاکنه</option>
<option
v-for="Supplier in Suppliers"
:key="Supplier.id"
:value="Supplier.id"
>{{ Supplier.name }}</option>
</select>
<has-error :form="form" field="supplier_id"></has-error>
</td>
<td style="width: 20%;padding-right: 10px;">
<input
dir="rtl"
id="text1"
v-model="invoice_product.date"
placeholder="نیټه "
type="date"
name="date[]"
class="form-control"
:class="{
'is-invalid': form.errors.has('date')
}"
/>
<has-error :form="form" field="date"></has-error>
</td>
<td style="width: 20%;padding-right: 10px;">
<input
dir="rtl"
id="text1"
v-model="invoice_product.totalAmount"
placeholder=" ټولی پیسی "
type="number"
name="totalAmount[]"
class="form-control"
:class="{
'is-invalid': form.errors.has(
'totalAmount'
)
}"
/>
<has-error :form="form" field="totalAmount"></has-error>
</td>
<td style="width: 40%;padding-right: 10px;">
<textarea
v-model="invoice_product.description"
placeholder="تشریح"
type="text"
name="description[]"
class="form-control"
:class="{
'is-invalid': form.errors.has(
'description'
)
}"
></textarea>
<has-error :form="form" field="description"></has-error>
</td>
</tr>
<button type="button" class="btn btn-info" #click="addNewRow">
<i class="fa fa-plus-circle"></i>
Add
</button>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">لغوه کړی</button>
<button
v-show="editMode"
:disabled="form.busy"
type="submit"
class="btn btn-success"
>تازه کړی</button>
<button
v-show="!editMode"
:disabled="form.busy"
type="submit"
class="btn btn-primary"
>خوندی کړی</button>
</div>
</div>
</form>
Sript in the Purchases Vue
data() {
return {
invoice_products: [
{
supplier_id: "",
totalAmount: "",
date: "",
description: ""
}
],
}
deleteRow(index, invoice_product) {
var idx = this.invoice_products.indexOf(invoice_product);
console.log(idx, index);
if (idx > -1) {
this.invoice_products.splice(idx, 1);
}
this.calculateTotal();
},
addNewRow() {
this.invoice_products.push({
supplier_id1: "",
totalAmount1: "",
date1: "",
description1: ""
});
},
createPurchase() {
axios
.post("api/Purchase", {
myArray: this.invoice_products
})
.then(() => {
$("#addNew").modal("hide");
toast.fire({
icon: "success",
html: "<h5> معلومات په بریالیتوب سره خوندي شول</h5>"
});
Fire.$emit("refreshPage");
this.form.reset();
})
.catch(er => {
console.log(er);
});
},
I found the solution
public function store(Request $request)
{
if ($purchases= $request->get('myArray')) {
foreach($purchases as $purchase) {
Purchase::create([
'supplier_id' => $purchase['supplier_id'],
'date' => $purchase['date'],
'totalAmount' => $purchase['totalAmount'],
'description' => $purchase['description']
]);
}
}
return response()->json();
}

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>

Vue js select box giving a couple of errors

I'm doing a site that uses laravel and vue js. The error I'm getting is this
[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "selected_parent"
and this
[Vue warn]: Error in v-on handler (Promise/async): "Error: Request failed with status code 404"
I can't see where I'm going wrong.
Here is my product.blade.php
#extends('layouts.public')
#section('content')
<div class="content_wrapper">
#foreach($single_product as $product)
<div class="row single_product_wrapper">
<div class="col-lg-8 col-md-12-col-sm-12 product_details">
#foreach($parent_product as $parent)
<h1>
{{ $parent->title }}
</h1>
<table style="width: 100%; height: 95px;" border="2" cellspacing="5" cellpadding="5">
<tbody>
<tr style="text-align: center;">
<td>
<strong>Code</strong>
</td>
<td>
<strong>Description</strong>
</td>
<td>
<strong>Price</strong>
</td>
</tr>
<tr style="text-align: center;">
<td>
{{ $parent->code }}
</td>
<td>
{{ $parent->description }}
</td>
<td>
{{ $parent->price }}
</td>
</tr>
</tbody>
</table>
#endforeach
<!-- BEGIN ADD TO CART FORM -->
<div id="app">
#foreach($parent_product as $parent)
<code-selection :products="{{ $parent_product }}" :children="{{ $parent->parent }}"></code-selection>
#endforeach
</div>
<!-- END ADD TO CART FORM -->
</div>
</div>
#endforeach
</div>
#stop
and this is my vue
<template>
<div>
<form #submit.prevent="submit">
<div class="row">
<div class="col-lg-12 code_select">
<select name="code" id="code" class="form-control mb-2 mt-10" v-model="selected_parent" required>
<option :value="selected_parent">Please select your code</option>
<option v-for="product in products" :value="product.id">
{{ product.code }}
</option>
<option v-for="child in children" :value="child.id">
{{ child.code }}
</option>
</select>
</div>
</div>
<input type="submit" class="btn btn-dark btn-lg btn-block" value="Add To Cart">
</form>
</div>
</template>
<script>
import axios from 'axios'
export default {
props: [
'products',
'children',
'selected_parent'
],
mounted() {
console.log('Component mounted.')
},
methods: {
submit(){
var formData = new FormData();
formData.append('code', this.selected_parent);
return axios.post('/add-to-cart/'+this.selected_parent, formData)
.then(
function(response)
{
console.log(response.data.redirect);
window.location = response.data.redirect;
}
);
},
},
}
</script>
So what I would like to happen is, when the user selects a code and hits the Add To Cart button they will then get taken to the cart page, but right now
that isn't happening when I select the code and hit the button nothing happens and I get the errors that I said in my console.
If there is anything else you need to know please let me know
The answer is simple, you should break the direct prop mutation by assigning the value to some local component variables(could be data property, computed with getters, setters, or watchers).
Here's a simple solution using the watcher.
<template>
<input
v-model="input"
#input="updateInput" />
</template>
<script>
export default {
props: {
value: {
type: String,
default: '',
},
},
data() {
return {
input: '',
};
},
watch: {
value: {
handler(after) {
this.input = after;
},
immediate: true,
},
},
methods: {
updateInput() {
this.$emit('input', this.input);
},
},
};
</script>
It's what I use to create any data input components and it works just fine. Any new variables sent by parent v-model will be watched and assigned to the input variable and once the input is received, catch that action and emit input to parent suggesting that data is input from the form element.
And for the second part, when you receive the new url from redirect, simply replace the location href like this:
return axios.post('/add-to-cart/'+this.selected_parent, formData)
.then((response) => {
window.location.href = response.data.redirect;
})
.catch((error) => {
console.log(error);
})
);

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]);
}

Child component mounts faster than parent

I use Laravel and Vue. I have two components: parent and child.
Parent:
<template>
<div>
<sport-sites-add :applications-all-list="applicationsAll"></sport-sites-add>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Application id</th>
<th scope="col">Name</th>
<th scope="col">Description</th>
<th scope="col">Picture</th>
<th scope="col">URL</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr v-for="sportSite in sportSites">
<th scope="row">{{ sportSite.id }}</th>
<td>
<template v-for="application in sportSite.applications">
id {{ application.id }} => {{ application.name }} <br>
</template>
</td>
<td>{{ sportSite.name }}</td>
<td>{{ sportSite.description }}</td>
<td>
<img style="width: 100px; height: 100px;" :src="sportSite.image" >
</td>
<td>
<a :href="sportSite.url" target="_blank">{{ sportSite.url }}</a>
</td>
<td>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import { EventBus } from '../../app';
export default {
name: "SportSitesTable",
mounted(){
this.loadTable();
this.getApplications();
},
methods:{
loadTable: function () {
window.axios.get('/sport_sites_all')
.then(resp => {
this.sportSites = resp.data.data;
}).catch(err => {
console.error(err);
});
},
getApplications: function () {
window.axios.get('/applications/all')
.then(resp => {
this.applicationsAll = resp.data.applications.data;
}).catch(err => {
console.error(err);
});
}
},
data(){
return {
sportSites: [],
applicationsAll: [],
}
},
}
</script>
Child:
<template>
<div>
<button type="button" class="btn btn-primary my-2" data-toggle="modal" data-target="#sportSiteAdd">
Add
</button>
<div class="modal fade" id="sportSiteAdd" tabindex="-1" role="dialog" aria-labelledby="sportSiteAddLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="sportSiteAddLabel">Add sport site</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<ul class="alert-danger">
<li v-for="error in errors">
{{ error[0] }}
</li>
</ul>
<form>
<div class="form-group">
<label for="name">Title</label>
<input type="text" class="form-control" id="name" name="name" v-model="formFields.name">
</div>
<div class="form-group">
<label for="image">Picture</label>
<input type="text" class="form-control" id="image" name="image" v-model="formFields.image">
</div>
<div class="form-group">
<label for="url">URL</label>
<input type="text" class="form-control" id="url" name="url" v-model="formFields.url">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control" id="description" name="description" v-model="formFields.description"></textarea>
</div>
<div>
<label class="typo__label">Applications </label>
<multiselect v-model="formFields.applications"
tag-placeholder="Applications"
placeholder="Search"
label="name"
track-by="id"
:options="applications"
:multiple="true"
:taggable="true">
</multiselect>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" v-on:click="submit">Save</button>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import { EventBus } from '../../app';
import Multiselect from 'vue-multiselect'
export default {
name: "SportSitesAdd",
props: ['applicationsAllList'],
methods:{
submit: function (e) {
window.axios.post('/sport_site/add/', this.formFields)
.then(res => {
console.log('Saved!');
$('#sportSiteAdd').modal('hide');
this.formFields.name = '';
this.formFields.image = '';
this.formFields.url = '';
this.formFields.description = '';
EventBus.$emit('reloadApplicationsTable');
}).catch(err => {
if(err.response.status === 422){
this.errors = err.response.data.errors || [];
}
console.error('Error of saving!');
});
},
},
data(){
return {
formFields: {
name: '',
image: '',
url: '',
description: '',
applications: this.applicationsAllList,
},
errors: [],
}
},
components: {
Multiselect
},
}
</script>
The parent component is a table. Child component is a form for the table. I pass a data from the parent to the child via props:
<sport-sites-add :applications-all-list="applicationsAll"></sport-sites-add>
In the child component I have a plugin for creating a multiple select. The plugin requires 'options' and 'values' collections. It's very simple, documentation with my case is here https://vue-multiselect.js.org/#sub-tagging. At the result I want to see the following: all items on the select are selected. But I have just the empty collection during mounting of the child component. I have available items on the 'select' but I dont know how I can make it selected by default. Obviously, I need to copy the applicationsAllList into local data() of child component and use it. But it not available during mounted and beforeMounted.
console.log tells me that the child is faster.
you're missing #tag function & v-model, in this case, must be array, You need to use applicationsAllList props directly on options
<multiselect v-model="formFields.value"
tag-placeholder="Applications"
placeholder="Search"
label="name"
track-by="id"
:options="applicationsAllList"
:multiple="true"
#tag="addTag"
:taggable="true">
</multiselect>
in methods add addTag function and add value as array
data() {
return {
formFields: {
name: '',
value: [],
image: '',
url: '',
description: '',
},
errors: [],
}
},
methods: {
addTag (newTag) {
const tag = {
name: newTag,
code: newTag.substring(0, 2) + Math.floor((Math.random() * 10000000))
}
this.options.push(tag)
this.value.push(tag)
}
}

Resources