Save multidimensional array using Laravel and ajax - ajax

I am building a pharmacy management system. I have a condition where I need to build a section
As shown in the picture, I need to store the data where the upper three should be same for all of the rows inputted below.
The form data is submitted as in the below picture.
But the data when looped and saved is not being saved as desired. Only the last row of the data is being inserted and I am also confused to store supplier, purchase date and note since these data should be repeated as many as the number of rows are added.
PurchaseController.php
public function storePurchase(PurchaseStoreRequest $request)
{
$purchase = new Purchase();
$count = count($request->name);
// return response()->json($request->all());
for ($i = 0; $i < $count; $i++) {
$purchase->supplier = $request->supplier;
$purchase->purchase_date = $request->purchase_date;
$purchase->description = $request->description;
$purchase->category = $request->category[$i];
$purchase->name = $request->name[$i];
$purchase->generic_name = $request->generic_name[$i];
$purchase->batch_number = $request->batch_number[$i];
$purchase->company = $request->company[$i];
$purchase->strength = $request->strength[$i];
$purchase->expiry_date = $request->expiry_date[$i];
$purchase->quantity = $request->quantity[$i];
$purchase->selling_price = $request->selling_price[$i];
$purchase->purchase_price = $request->purchase_price[$i];
$purchase->save();
}
return response()->json(['message' => 'Purchase Saved Successfully']);
}
Can someone help me to store these three fields in the database repeating the number of rows submitted ?
Currently only the last row is being inserted into the database.

This might be an another way to accomplish what you're looking for.
$sharedKeys = ['supplier', 'purchase_date', 'description'];
$sharedData = $request->only($sharedKeys);
$multiKeys = ['category', 'name', 'generic_name', 'batch_number', 'company', 'strength', 'expiry_date', 'quantity', 'selling_price', 'purchase_price'];
$multiData = $request->only($multiKeys);
for ($i = 0; $i < count($request->name); $i++) {
$individualData = array_combine($multiKeys, array_column($multiData, $i));
Purchase::create($sharedData + $individualData);
}

For every loop, you need to create a new instance, then It will create a new record on each loop :
public function storePurchase(PurchaseStoreRequest $request)
{
// $purchase = new Purchase();
$count = count($request->name);
// return response()->json($request->all());
for ($i = 0; $i < $count; $i++) {
$purchase = new Purchase(); // create new instance end with (); on each loop
$purchase->supplier = $request->supplier;
$purchase->purchase_date = $request->purchase_date;
$purchase->description = $request->description;
$purchase->category = $request->category[$i];
$purchase->name = $request->name[$i];
$purchase->generic_name = $request->generic_name[$i];
$purchase->batch_number = $request->batch_number[$i];
$purchase->company = $request->company[$i];
$purchase->strength = $request->strength[$i];
$purchase->expiry_date = $request->expiry_date[$i];
$purchase->quantity = $request->quantity[$i];
$purchase->selling_price = $request->selling_price[$i];
$purchase->purchase_price = $request->purchase_price[$i];
$purchase->save();
}
return response()->json(['message' => 'Purchase Saved Successfully']);
}

Related

Display large array in laravel blade in too much time

so i got imported my large excel file with huge informations with 1 sec and i did get all the information i need to display within 1 sec to , but i got a big probleme when displaying the array in the view coz i m testing if the cells are correct or not i m using 5 ifs and 3 foreach and it takes mote than 2 mins , i need help to display all the info in a short time this is my array , and thanks
and there is my code of the view which takes to much time to display infos
and thanks
//here we get our final result of true and false fields
$finale_array = [];
// here we get all our
$current_table2 = [];
$results_applied = [];
$current_result = [];
$columns = SCHEMA::getColumnListing('imports');
// here we get all our conditions
$conditions = DB::table('conditions')->select('number', 'field', 'value')->get();
// here we get all our data
$imports = DB::table('imports')->get();
$results = DB::table('results')->get();
$x = 0;
$default_value = 0;
foreach ($imports as $key => $imported) {
$res = get_object_vars($imported);
foreach ($conditions as $value) {
$array = get_object_vars($value);
$result = $this->test($columns, $array['field']); // the result of our test function
if ($result == "ok") {
if ($res[$array['field']] == $array['value']) {
foreach ($results as $value_result) {
$res_resultat = get_object_vars($value_result);
$test_field = $this->test($columns, $res_resultat['field']);
// testing if the condtion numder match with the result number
if (($res_resultat['condition_number'] == $array['number'])) {
if (($test_field == 'ok')) {
if ($res['id'] != $default_value) {
// here test if the difference between the id and the default value is different from the current id to insert
if (($res['id'] - $default_value) != $res['id']) {
array_push($current_table2, $results_applied);
array_push($finale_array, $current_table2);
$current_table2 = [];
$results_applied = [];
$default_value = $res['id'];
}
$current_table2 = [$res, $res['id']];
}
$current_result = [$res_resultat['field'], $res[$res_resultat['field']]];
if ($res_resultat['value'] == $res[$res_resultat['field']]) {
$current_result[2] = 'true';
$current_result[3] = $res_resultat['value'];
} else {
$current_result[2] = 'false';
$current_result[3] = $res_resultat['value'];
}
$current_result[4] = $array['number'];
array_push($results_applied, $current_result);
}
}
}
}
}
}
$default_value = $res['id'];
}
array_push($current_table2, $results_applied);
array_push($finale_array, $current_table2);
dd($finale_array);
return view('Appliedconditions', ['imports' => $finale_array, 'columns' => $columns]);
}
From what I can see, you are recovering all the data without paging it.
You must paginate the data using the paginate(#elements_per_page) directive in your query, where #elements_per_page is the number of elements you want to display per page.
For example:
$elements = Elements::select('*')->paginate(10);
and in your blade view you can retreive pagination links after the closing table tag in this way: {{ $elements->links() }}

ErrorException : Undefined offset: 0

on my array push i want to concat the 2 data if they have the same date
$goal = Goal::where('employee_id',Auth::user()->employees->first()->id)
->with('accomplishments')->orderBy('date','asc')->get();
$next_week = $goal->whereBetween('date',[$add_start_date,$add_end_date]);
$last_week = $goal->whereBetween('date',[$sub_start_date,$sub_end_date]);
$goals = [];
$date = "";
for ($i=0; $i < count($next_week); $i++) {
if($next_week[$i]['date']==$date){
$goals[$i-1]['activity'] = $goals[$i-1]['activity'] .', '. $next_week[$i]['activity'];
continue;
}
array_push($goals,$next_week[$i]);
$date = $next_week[$i]['date'];
}
when using filtering on laravel collections, indexes are lost,
to re_index the result array, use 'values':
$next_week = $goal->whereBetween('date',[$add_start_date,$add_end_date])->values();
$last_week = $goal->whereBetween('date',[$sub_start_date,$sub_end_date])->values();

Why enter laravel loop data max 40 row?

I created a store function on my controller. At the time I will enter data with just one submit, only indexed up to 40 data will be entered. While those 40 and above do not enter the database. Why did this happen? What's the solution? Please i need help.
Sorry for my bad English.
Thanks
I am use Laravel 5.6
public function store(Request $request)
{
//
foreach($request->quantity as $quantity){
if($quantity == NULL){
}
if($quantity != NULL){
$data = new KomponenOlahan;
$data->quantity = $quantity;
$harga_satuan_mu = Input::get('harga_satuan_mu');
$total = $quantity*$harga_satuan_mu;
$data->kode_proyek = Input::get('kode_proyek');
$data->nama_proyek = Input::get('nama_proyek');
$data->kode_panel = Input::get('kode_panel');
$data->nama_panel = Input::get('nama_panel');
$data->schedule_kirim = Input::get('schedule_kirim');
$data->nama_sales = Input::get('nama_sales');
$data->ukuran_panel = Input::get('ukuran_panel');
$data->ref = Input::get('ref');
$data->type = Input::get('type');
$data->komponen_bantu = Input::get('komponen_bantu');
$data->nama_komponen = Input::get('nama_komponen');
$data->spek = Input::get('spek');
$data->satuan = Input::get('satuan');
$data->diskon = Input::get('diskon');
$data->harga = Input::get('harga');
$data->pole = Input::get('pole');
$data->ka = Input::get('ka');
$data->ampere = Input::get('ampere');
$data->quantity = $quantity;
$data->harga_satuan_mu = $harga_satuan_mu;
$data->harga_satuan_mb = Input::get('harga_satuan_mb');
$data->harga_satuan_lb_oh = Input::get('harga_satuan_lb_oh');
$data->id_estimasi = Input::get('id_estimasi');
$data->nama_estimasi = Input::get('nama_estimasi');
$data->total = $total;
$data->trigger_bom = Input::get('trigger_bom');
$data->save();
}
}
My View
<td><input type="text" name="quantity[]" class="form-control"></td>
<td><input type="text" name="kode_proyek" hidden value="{{$panel->kode_projek}}">
etc....
My View
my view
You can save it first to array then use bulk insert.
Inserting data 1 by 1 will slow your application.
$insertArray = array();
foreach($request->quantity as $quantity){
if($quantity == NULL){
$insertArray[] = array(
'quantity' => $quantity,
'harga_satuan_mu ' => Input::get('harga_satuan_mu'),
.... // add other fields
)
}
}
KomponenOlahan::insert($insertArray);

Passing multiple values using

I want to pass multiple values in single column of database.
I have two tables (Schedule & Days). In form I select days when I select multiple days then I should add in db multiple. But it add only one day
public function store(Request $request)
{
$schedule = new menu;
$days = new day;
$sensor = new sensor;
$schedule->scheduleName = $request->name;
$schedule->start_time = $request->start_time;
$schedule->end_time = $request->end_time;
$schedule->timestamps = false;
$schedule->s_daytime = $request->s_daytime;
$schedule->e_daytime = $request->e_daytime;
$days->days = $request->days;
$days->timestamps = false;
$sensor->timestamps = false;
$sensor->sensor = $request->sensor;
$schedule->save();
$days->schedule_id = $schedule->id;
$days->save();
$sensor->schedule_id = $schedule->id;
$sensor->save();
return view('store');
}
What you can do is you can pass multiple days in an array and store the array in json format on your DB. here is the snippets.
$days_list = $request->days_list;
//for edit previous data
if(!empty($days->days_list)){
$arr = json_decode($days->days_list);
if(in_array($request->days, $arr)){
$data['success'] = false;
$data['message'] = 'This Day is already on your schedule
list.';
return $data;
}
array_push($arr, $days_list);
$days->days_list = json_encode($arr);
}
// for adding new data
else{
$days->days_list = json_encode(array($request->days_list));
}
$days->save();
```

Laravel 5.3 database transaction issue?

I have used more time with Laravel 5.0 on database transaction but when I change to Laravel 5.3.* it not work as I want even I have disabled commit() method all data still continue insert into database.
if ($request->isMethod('post')) {
DB::beginTransaction();
$cats = new Cat();
$cats->parent_id = $this->request->input('category_id');
$cats->status = ($this->request->input('status')) ? $this->request->input('status') : 0;
if ($res['cat'] = $cats->save()) {
$catD = new CategoryDescriptions();
$catD->category_id = $cats->id;
$catD->language_id = 1;
$catD->name = $this->request->input('en_name');
if ($res['cat2'] = $catD->save()) {
$catD2 = new CategoryDescriptions();
$catD2->category_id = $cats->id;
$catD2->language_id = 2;
$catD2->name = $this->request->input('kh_name');
$res['all'] = $catD2->save();
}
}
if ($res) {
//DB::commit();
return $res;
}
return [false];
}
Check this line ($res['cat'] is a boolean):
if($res['cat'] = $cats->save()) {
And this ($res is an array. You compare an array as boolean!):
if($res){
The right condition should be:
$res = array(); // the first line of your method
// .... your http method check, start transaction, etc.
if (!in_array(false, $res, true)) { // check if array doesn't contain 'false values'
DB::commit();
}

Resources