message: "Undefined index: SKU" - laravel

When i do dd($data); all data will shown but when i remove dd and simply submit my form then problem always come undefined index sku.
This is my controller for product attribute
public function addProductAttributes(Request $request){
if($request->isMethod('post')){
$data=$request->all();
foreach($data['sku'] as $key => $value){
if($value != null){
$attr = new ProductsAttribute();
$attr->product_id = $data['product_id'][$key];
$attr->sku = $data['sku'][$key];
$attr->stock=$data['stock'][$key];
$attr->price= $data['price'][$key];
$attr->size= $data['size'][$key];
$attr->status= $data['status'][$key];
$attr->save();
}
}
}
if($request->expectsJson()){
return response()->json([
'message'=>'Product has been Update Successfully',
]);
};
}
This is my Product Attribute Template. This is Dynamically Add / Remove input fields in Vue js so i can i add multiple data array
<form role="form" method="POST" #submit.prevent="addProductAttribute">
<table >
<tbody>
<tr v-for="(attr,index) in attribute" :key="index">
<td><input type="text" v-model="product_id" class="form-control"></td>
<td><input type="text" v-model="attr.sku" placeholder="SKU" class="form-control"></td>
<td><input type="text" v-model="attr.size" placeholder="Size" class="form-control"></td>
<td><input type="text" v-model="attr.stock" placeholder="Stock" class="form-control"></td>
<td><input type="text" v-model="attr.price" placeholder="Price" class="form-control"></td>
<td><input type="text" v-model="attr.status" placeholder="Status" class="form-control"></td>
<td><a #click="addAttribute()" v-show="index == attribute.length-1" title="Add More Product Attribute"><i class="fas fa-plus" style="color: #00b44e"></i></a> <a title="Remove" #click="removeAttribute(index)" v-show="index || ( !index && attribute.length > 1)"><i class="fas fa-minus" style="color: red"></i></a></td>
</tr>
</tbody>
<tfoot>
<tr><button type="submit" class=" btn-outline-primary btn-lg">Add</button></tr>
</tfoot>
</table>
</form>
and my Script file is
<script>
export default {
mounted() {
let app = this;
let id = app.$route.params.id;
app.product_id = id;
this.readProductAttribute();
},
data(){
return{
product_id:'',
product_name:'',
attributes:[],
product:'',
attribute:[
{
product_id:'',
sku:'',
price:'',
stock:'',
size:'',
status:'',
}
]
}
},
methods: {
removeAttribute(index){
this.attribute.splice(index, 1);
},
addAttribute(){
this.attribute.push({ size: '',sku:'',price:'',stock:'',status:'' });
},
addProductAttribute: function(e){
axios.post(`/admin/add-product-attribute`,{
myArray: this.attribute
})
.then(function(response){
console.log(response);
})
}
}
}

Your data lies within the key 'myArray' so changing the loop to the following should help on your error.
foreach($data['myArray'] as $key => $value){
The access logic for each attr is also flawed. You should only access it on their key, secondly it seems like product_id is not always there in your data, so you can use nullcoalescent to return empty string if key is not there.
$attr->product_id = $data['product_id'] ?? '';
$attr->sku = $data['sku'] ?? '';
$attr->stock=$data['stock'] ?? '';
$attr->price= $data['price'] ?? '';
$attr->size= $data['size'] ?? '';
$attr->status= $data['status'] ?? '';

Related

How to import data from excel file to mysql using vue Js and Laravel

I am having a problem trying to export an excel file to database using axios. Am able to console the file
but cant figure out to post the data.
I get this error
Failed to load resource: the server responded with a status of 422 (Unprocessable Entity) app.js:716
My view
<form enctype="multipart/form-data">
#csrf
<div class="form-group">
<table class="table">
<tr>
<td width="40%" align="right"><label>Select File for Upload</label></td>
<td width="30">
<input type="file" #change="getExcelData" name="select_file" />
</td>
<td width="30%" align="left">
<input type="submit" name="upload" class="btn btn-primary" value="Upload">
</td>
</tr>
</table>
</div>
</form>
The vue function
getExcelData(e){
//const formData = new FormData();
const file = e.target.files[0];
console.log(file);
//formData.append('file', file);
axios.post("/import_excel/import").then(function(response){
// this.users=response.data;
console.log("working now");
console.log(file);
console.log(response)
}.bind(this))
},
My controller file
function import(Request $request)
{
$this->validate($request, [
'select_file' => 'required|mimes:xls,xlsx'
]);
$path = $request->file('select_file')->getRealPath();
$data = Excel::load($path)->get();
if($data->count() > 0)
{
foreach($data->toArray() as $key => $value)
{
foreach($value as $row)
{
$insert_data[] = array(
'userName' => $row['userName'],
'userPassword' => $row['userPassword'],
'timePackage' => $row['timePackage'],
'location' => $row['location'],
'Assigned' => $row['Assigned']
);
}
}
if(!empty($insert_data))
{
DB::table('hotspot_users')->insert($insert_data);
}
}
return back()->with('success', 'Excel Data Imported successfully.');
}
Route
Route::post('/import_excel/import', 'ImportExcelController#import');

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

When I generate a PDF, text is working but image is not showing. How can I solve this?

When I generate a PDF, the text is working but the image is not showing an image. How can I solve this? How can I use an image in my PDF? In the below I have given some code of my problem.
This is the view code: all of the code is included in one field in the database.
view code :
<div class="tab-pane" id="sixweekletterwithauto" role="tabpanel" aria-labelledby="sixweekletterwithauto-tab">
<form action="patient/addcaseHistory" method="post" enctype="multipart/form-data">
<center>
<h2 style="margin-top: 0;color:#55518a">Case Notes</h2>
<textarea name="editor1" class="ckeditor">
<img src="../uploads/pic.jpg" width="1000px" height="200px">
<p> </p>
<table align="right" style="width:200px">
<tbody>
<tr>
<td> Dr M Takla</td>
</tr>
<tr>
<td> 621 Boronia Rd Wantirna South</td>
</tr>
<tr>
<td> VIC 3152</td>
</tr>
<tr>
<td> Ph 97380009 Fax</td>
</tr>
</tbody>
</table>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p>Dear Dr M Takla,,</p>
<p><strong>Re: Aryan Karat (DOB : 9/12/2008)</strong></p>
<p>Thank you for referring Aryan Karat, for assistance with “behaviour problems, hyperactivity and phobias”.</p>
<p>The therapeutic process with Aryan has focussed on reducing anxiety and improving self confidence and self esteem. I have worked on a number of cognitive and behavioural strategies to assist Aryan in managing his worry. His teacher and parents have reported some positive changes, however they continue to be concerned about his constant need for reassurance by adults and anxiety in some situations.</p>
<p>Further sessions with Aryan are recommended in order to ensure that the skills and strategies imparted can be reinforced and fully assimilated.</p>
<p>If you wish to discuss this matter further, I may be contacted at 0419 489 333.</p>
<p>Thank you again for your referral, and I look forward to your reply.</p>
<p>Yours Sincerely</p>
<p> </p>
<p>Ms Angela Delle-Vergini,<br />
Psychologist<br />
M.A.P.S (B.A, Grad Dip Psych, M.Psych (Counselling).</p>
<p> </p>
</textarea>
<script>
CKEDITOR.replace( 'editor2' );
CKEDITOR.add
</script>
</center>
<input type="hidden" name="patient_id" value='<?php echo $patient->id; ?>'>
<input type="hidden" name="date" value='<?php echo date('m-d-Y') ?>'>
<div style="margin-bottom: 30px;">
<button class="btn btn-blue">Save & Finalise</button>
</div>
</form>
</div>
controller code :
function addcaseHistory() {
$id = $this->input->post('id');
$patient_id = $this->input->post('patient_id');
$date = $this->input->post('date');
$description = $this->input->post('editor1');
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$redirect = $this->input->post('redirect');
if (empty($redirect)) {
$redirect = 'patient/medicalHistory?id=' . $patient_id;
}
// Validating Name Field
$this->form_validation->set_rules('date', 'Date', 'trim|required|min_length[5]|max_length[100]|xss_clean');
// Validating Password Field
$this->form_validation->set_rules('editor1', 'Description', 'trim|required|min_length[5]|max_length[10000]|xss_clean');
if ($this->form_validation->run() == FALSE) {
if (!empty($id)) {
redirect("patient/editMedicalHistory?id=$id");
} else {
$this->load->view('home/dashboard'); // just the header file
$this->load->view('add_new');
$this->load->view('home/footer'); // just the header file
}
} else {
if (!empty($patient_id)) {
$patient_details = $this->patient_model->getPatientById($patient_id);
$patient_name = $patient_details->name;
$patient_phone = $patient_details->phone;
$patient_address = $patient_details->address;
} else {
$patient_name = 0;
$patient_phone = 0;
$patient_address = 0;
}
//$error = array('error' => $this->upload->display_errors());
$data = array();
$data = array(
'patient_id' => $patient_id,
'date' => $date,
'description' => $description,
'patient_name' => $patient_name,
'patient_phone' => $patient_phone,
'patient_address' => $patient_address,
);
if (empty($id)) { // Adding New department
$this->patient_model->insertMedicalHistory($data);
$this->session->set_flashdata('feedback', 'Added');
} else { // Updating department
$this->patient_model->updateMedicalHistory($id, $data);
$this->session->set_flashdata('feedback', 'Updated');
}
// Loading View
$data['settings'] = $this->settings_model->getSettings();
$this->load->view('home/dashboard2',$data); // just the header file
$this->load->view('medical_history', $data);
$this->load->view('home/footer'); // just the footer file
}
}
public function pdfdetails()
{
$id = $this->input->get('id');
$html_content .= $this->patient_model->getMedicalHistoryByPatientId2($id);
$this->pdf->loadHtml($html_content);
$this->pdf->render();
$this->pdf->stream("".$id.".pdf", array("Attachment"=>0));
}
Model code:
function getMedicalHistoryByPatientId2($id)
{
$this->db->where('id', $id);
$data = $this->db->get('medical_history');
foreach($data->result() as $row)
{
$output .= '<p>'."<img src='../uploads/'".$row->img_url."/>".$row->description.'</p>';
}
return $output;
}

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

VueJS linked inputs

I would like to link multiple inputs via VueJS and compute the values.
The inputs are to track vehicle mileage, and therefore any given day's value, cannot be less than the previous day's value.
So far I have come up with the following (it's very convoluted and I know it can be tidied up but I'll improve on that later). It doesn't work, as you can't change any value apart from Monday Start.
https://jsfiddle.net/mstnorris/qbgtpm34/1/
HTML
<table id="app" class="table">
<thead>
<tr>
<th>Day</th>
<th>Start</th>
<th>End</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Mon</th>
<td>
<input type="number" class="form-control" v-model="mon_start" number id="mon_start" placeholder="Monday Start Mileage">
</td>
<td>
<input type="number" class="form-control" v-model="mon_end" number id="mon_end" placeholder="Monday End Mileage">
</td>
</tr>
<tr>
<th scope="row">Tue</th>
<td>
<input type="number" class="form-control" v-model="tue_start" number id="tue_start" placeholder="Tuesday Start Mileage">
</td>
<td>
<input type="number" class="form-control" v-model="tue_end" number id="tue_end" placeholder="Tuesday End Mileage">
</td>
</tr>
<tr>
<th scope="row">Wed</th>
<td>
<input type="number" class="form-control" v-model="wed_start" number id="wed_start" placeholder="Wednesday Start Mileage">
</td>
<td>
<input type="number" class="form-control" v-model="wed_end" number id="wed_end" placeholder="Wednesday End Mileage">
</td>
</tr>
<tr>
<th scope="row">Thu</th>
<td>
<input type="number" class="form-control" v-model="thu_start" number id="thu_start" placeholder="Thursday Start Mileage">
</td>
<td>
<input type="number" class="form-control" v-model="thu_end" number id="thu_end" placeholder="Thursday End Mileage">
</td>
</tr>
<tr>
<th scope="row">Fri</th>
<td>
<input type="number" class="form-control" v-model="fri_start" number id="fri_start" placeholder="Friday Start Mileage">
</td>
<td>
<input type="number" class="form-control" v-model="fri_end" number id="fri_end" placeholder="Friday End Mileage">
</td>
</tr>
<tr>
<th scope="row">Sat</th>
<td>
<input type="number" class="form-control" v-model="sat_start" number id="sat_start" placeholder="Saturday Start Mileage">
</td>
<td>
<input type="number" class="form-control" v-model="sat_end" number id="sat_end" placeholder="Saturday End Mileage">
</td>
</tr>
<tr>
<th scope="row">Sun</th>
<td>
<input type="number" class="form-control" v-model="sun_start" number id="sun_start" placeholder="Sunday Start Mileage">
</td>
<td>
<input type="number" class="form-control" v-model="sun_end" number id="sun_end" placeholder="Sunday End Mileage">
</td>
</tr>
</tbody>
</table>
VueJS
new Vue({
el: "#app",
data: {
mon_start: '',
mon_end: '',
tue_start: '',
tue_end: '',
wed_start: '',
wed_end: '',
thu_start: '',
thu_end: '',
fri_start: '',
fri_end: '',
sat_start: '',
sat_end: '',
sun_start: '',
sun_end: ''
},
computed: {
mon_end: function() {
return this.mon_start
},
tue_start: function () {
return this.mon_end
},
tue_end: function() {
return this.tue_start
},
wed_start: function () {
return this.tue_end
},
wed_end: function() {
return this.wed_start
},
thu_start: function () {
return this.wed_end
},
thu_end: function() {
return this.thu_start
},
fri_start: function () {
return this.thu_end
},
fri_end: function() {
return this.fri_start
},
sat_start: function () {
return this.fri_end
},
sat_end: function() {
return this.sat_start
},
sun_start: function () {
return this.sat_end
},
sun_end: function() {
return this.sun_start
}
}
})
Why does this not work so far?
You are mixing data property names with computed properties, so the value will be read from the computed property (get) and it will try to write it back to the same computed property, which wont work since you haven't assigned a setter.
Also, always showing the value of mon_start in mon_end etc. will not allow you to show the updated value of mon_end in mon_end.
Computed: Getters and Setters
What you actually want is a custom action to happen when a new value is set (e.g. mon_start is set to 2, thus all other fields should be set to 2).
Now we could just say: If mon_start is updated, update mon_end. If mon_end is updated, update tue_start. And so on.
This can be achieved using computed setters:
mon_start_model: {
get: function() {
return this.mon_start
},
set: function(val) {
this.mon_start = val
this.mon_end_model = this.mon_start
}
},
I've simplified the example a little bit (using only Monday and Tuesday).
Avoiding confusing the user
As an extra condition for user-friendliness, you probably only want the next value to update if the next value is smaller or equal to the previous value.
Eg. mon_start is 1 at the beginning, then you update mon_end to 5, then you update mon_start to 3. You probably want mon_end to keep the value 5, right?
new Vue({
el: "#app",
data: {
mon_start: 0,
mon_end: 0,
tue_start: 0,
tue_end: 0,
},
computed: {
mon_start_model: {
get: function() {
return this.mon_start
},
set: function(val) {
this.mon_start = val
this.mon_end_model = Math.max(this.mon_end, this.mon_start)
}
},
mon_end_model: {
get: function() {
return this.mon_end
},
set: function(val) {
this.mon_end = val
this.tue_start_model = Math.max(this.tue_start, this.mon_end)
}
},
tue_start_model: {
get: function () {
return this.tue_start
},
set: function(val) {
this.tue_start = val
this.tue_end_model = Math.max(this.tue_end, this.tue_start)
}
},
tue_end_model: {
get: function() {
return this.tue_end
},
set: function(val) {
this.tue_end = val
}
}
}
})
https://jsfiddle.net/qbgtpm34/5/

Resources