Update fields using foreach in Laravel PHP - php

I'm trying to update multiple rows based on its unique field taskCode
and will update the field of taskWeight from tbl_projtask
I have this 2 variable
$request->dataWeight
This variable is coming from ajax request that contains something like this 95,75,65 a value that is separated by commas.
$request->dataWeightAttr
This variable is coming from ajax request that contains something like this TaskCode1, TaskCode2, TaskCode3
In my MainController.php
I have this code
$myString = $request->dataWeightAttr;
foreach($myString as $value){
DB::table('tbl_projtask')
->where('taskCode', $value)
->update([
'taskWeight'=> $request->dataWeight,
'by_id'=> auth()->user()->id,
'updated_by'=> auth()->user()->name,
'updated_at' => now()
]);
}
As you can see in my update code
I used request->dataWeightAttr to find which rows should be updated and $request->dataWeight the value for specific taskCode
Am I doing this right?

Convert your string to an Array
$dataWeight = explode(',',$request->dataWeight); // convert to array
$dataWeightAttr = explode(',',$request->dataWeightAttr); // convert to array
Assuming you have related values in both array.
foreach($dataWeightAttr as $key => $value){
DB::table('tbl_projtask')
->where('taskCode', $value)
->update([
'taskWeight'=> $dataWeight[$key],
'by_id'=> auth()->user()->id,
'updated_by'=> auth()->user()->name,
'updated_at' => now()
]);
}

You can use whereIn instead of foreach if you want to update same fields but different id.
DB::table('tbl_projtask')
->whereIn('taskCode', $request->dataWeightAttr)
->update([
'taskWeight'=> $request->dataWeight,
'by_id'=> auth()->user()->id,
'updated_by'=> auth()->user()->name,
'updated_at' => now()
]);

Related

how do i subtract from a form request and update laravel db

i want a form to substract from the amount in accounts table
help me out. here is my code
public function transferSend(Request $request)
{
$request->validate([
'rec_acc_name' => 'required',
'swift_code' => 'required',
'rou_no' => 'required',
'rec_bank_add' => 'required',
'trans_amou' => 'required',
'remarks' => 'required',
]);
$balance = DB::table('accounts')->pluck('amount');
if($request->trans_amoun < $balance)
{
return ('you don no have enough balance');
} else{
$request->trans_amoun = $trans_amoun
$newbalance = $trans_amoun
$newbalance = DB::table('accounts')
->update('amount');
}
i'm new to php and laravel please help
PHP code requires ; at the end of every statement. You can't leave them out. This isn't javascript.
Updating the request has no effect. This code does nothing.
$request->trans_amoun = $trans_amoun;
You have no WHERE clause so your query is getting all the rows in the table. You then proceed to use the returned data as if it is a single value.
Let;s say the accounts table had a column named id, you would do something like this:
$balance = DB::table('accounts')
->where('id', $request->id)
->value('amount');
The above code will return a single value.
Read this:
https://laravel.com/docs/9.x/queries#retrieving-a-single-row-column-from-a-table
You state you are trying to subtract an amount so you need to take the amount from the database and subtract the amount in the request.
$newbalance = $balance - $request->trans_amount;
The update code is broken. It also needs to know which row to update. You also have to give it the columns you want to update and the new values for those columns.
DB::table('accounts')
->where('id', $request->id)
->update(['amount' => $newbalance]);
Read this:
https://laravel.com/docs/9.x/queries#update-statements
I really recommend that you spend some time reading the laravel docs.

Is there a way to avoid updating all data when using update_batch()?

My current problem is that all data are being updated all at once when I use update_batch(), is there a way to update only the last data?
I am updating grades every semester that is why I need to update the latest grades in this semester. However whenever I update grades, the latest update will also update the previous grades in my semester that is why it is being overwritten. Hence, I only want to update the latest grades in this semester. I also used update_batch to update multiple records, am I wrong doing so?
Here is my controller:
$schoolYear = $csvData[0]['schoolYear'];
$semester = $csvData[0]['semester'];
$studentIDFromDB = $this->importSISAcademicInformationGetStudentIDFromDB($schoolYear, $semester);
foreach ($csvData as $key => $value) {
if(isset($studentIDFromDB[$value['studentID']])){
$updateFields[$key] = array(
'studentID' => $value['studentID'],
'programType' => $value['programType'],
'level' => $value['level'],
'sectionDescription' => $value['sectionDescription'],
'schoolYear' => $value['schoolYear'],
'semester' => $value['semester']
);
}
}
if(isset($updateFields))
$this->DBLogic->updateBatchRecordMultipleCondition('tbl_tt_academicinfo', $updateFields, 'studentID', array('schoolYear' => $schoolYear, 'semester' => $semester));
Here is my Model:
public function updateBatchRecordMultipleCondition($table, $fields, $criteria1, $criteriaN){
$this->db->where($criteriaN);
$this->db->update_batch($table, $fields, $criteria1);
}
In Codeigniter 3.x, the function batch_update(), as by documentation has its where clause set in the 3rd parameter of the function and not by a preceding where() clause.
without knowing anything else about your variables and data, most likely this will do it:
$this->db->update_batch($table, $fields, $criteriaN);
Anyway, make sure you follow these indications from doc:
update_batch($table[, $set = NULL[, $value = NULL[, $batch_size = 100]]])
Parameters:
$table (string) – Table name
$set (array) – Field name, or an associative array of field/value pairs
$value (string) – Field value, if $set is a single field
$batch_size (int) – Count of conditions to group in a single query
Returns:
Number of rows updated or FALSE on failure
hint: In case you cannot set the where clause in the update_batch() function, use the update() function - which allows you to set a preceding where() - within you foreach loop.

Use relation (for ex. belongsTo) inside KeyValue field in Laravel Nova

Laravel: 8.51
Nova: 3.24
PHP Version: 7.4.20
I have problem with trying to solve this situation:
I have a action that uses a KeyValue to handle array of pairs: "product_id" and "amount"
field looks like:
KeyValue::make(__('Order details'), 'details')
->rules('json'),
also in model i added cast:
protected $casts = [
'details' => 'array',
];
I convert it to json and store in database like that
foreach ($fields->details as $key => $value)
{
$order_details[$key] = $value;
}
//(...)
DB::table('orders')->InsertGetId([
'details' => json_encode($order_details),
]);
finnaly my json field in database looks like:
{"1":"6","2":"7","3":"8"}
To this point everything works great.
Now I want to change what I see as product_id (in above example 1, 2, 3) to be from other resource like belongsTo('products')
I was considering how to be able to use BelongsTo or Select in key part of KeyValue field.
I tried few ways to display it somehow in stack field like:
Stack::make('Details', [
Text::make('details', function () {
return $this->details($key); // how to properly read $key from json in fields?
}),
Text::make('amount',function () {
return $this->details($value); // how to properly read $value from json in fields?
}),
]),
or
BelongsTo::make(__('Product'), 'user', Products::class)
->withMeta([
'belongsToId' => $this->details($key), // again i dont know how to properly read $key here from json.
]),

How to handle array with laravel requests?

I am using the simple form and array input like this (not dynamic)
<input type="text" name="pre_ref_position[]" id="pre_ref_position">
<input type="text" name="pre_ref_position[]" id="pre_ref_position">
Form post with ajax and return data like this;
[
0:{pre_ref_position:'example1'}
1:{pre_ref_position:'example2'}
]
So I want to save this data with eloquent but how can I handle this array and save each row in the database?
Assuming you receive your array in a variable called $refValin your controller
Then use the following code:
$refArr = [];
foreach($refVal as $key => $val)
{
$now = Carbon::now();
//ref_pos in the array below refers to the field name in your database.
$refArr[] = [ 'ref_pos' => $val['pre_ref_position'] ,'created_at' => $now, 'updated_at' => $now ];
}
//assuming model name is `Position`
Position::insert($refArr);

Insert dynamic Object property names into Database

Alright so I have an insert query that I would like to run but the issue I am having is with getting object properties/values that I need to insert.
Say I have a query that looks like the one below.
$this->db->insert('tblitems_in', array(
'platform' => $item['Platform'],
'ram' => $item['RAM'],
'qty' => $item['qty'],
'rate' => number_format($item['rate'], 2, '.', ''),
'rel_id' => $insert_id,
'rel_type' => 'estimate',
'item_order' => $item['order'],
'unit' => $item['unit']
));
This works fine when the person chooses RAM on the webpage which sets the $item Objects property 'RAM' to the value that was picked. Now if they choose HardDrive, that properties name is now sent as 'HardDrive' with the value they chose. Is there a way that i Could replace the 'ram' and 'RAM' from the below example with a variable so I could change what the property name is that I would like to insert and insert into the corresponding db column?
EDIT:
I should have added that the options on the webpage are also dynamically created from a database so I do not know at the time of coding what the property names are. They could be RAM, HardDrive, Processor, maybe even Elephant. I was hoping I could use variables so that I could look at the DB used to create the webpage so that I know the property names and then dynamically add those names into the query.
EDIT:
Right now I am using the following code in order to get all the possible options that can be received from the webpage from a DB the webpages uses to create itself.
$plat_options = $this->db->get('tblplatform_options')->row()->name;
In the database right now it is only populated with names RAM and HardDrive to make things known for testing purposes. So this returns $plat_options = {RAM, HardDrive}. I now have to figure out how to test is $item has these(RAM and HardDrive) as properties and if $item does have them then add them into the query previously shown.
You can set an array of key => variable names, then loop over those values to see if they exist in the $item variable and, if so, add that value to the data to be inserted into the db:
//default array of data to insert
$data = [
'platform' => $item['Platform'],
'qty' => $item['qty'],
'rate' => number_format($item['rate'], 2, '.', ''),
'rel_id' => $insert_id,
'rel_type' => 'estimate',
'item_order' => $item['order'],
'unit' => $item['unit']
];
//Get column names from db
$plat_options = $this->db->get('tblplatform_options')->row()->name;
// $plat_options = [RAM, HardDrive]
//Check if $item[$name] exists. If it does, add that to the
// array of data to be inserted
foreach($plat_options as $key) {
if(array_key_exists($key, $item)) {
$data[$key] = $item[$key];
}
}
$this->db->insert('tblitems_in', $data);
edit
I'm not sure this will work (I don't understand the use case).
It is possible, using array_diff_key to get a list of array keys that exist in $item but not in $data. With this array of keys, you can add the missing keys.
I have altered my previous code to demonstrate this.
You could create the array one element at a time based on whatever field data you received. I used a switch statement, but it could be a simple if/then/else as well.
$data_array = array();
$data_array['platform'] = $item['Platform']
switch($item['Object'] {
case 'HardDrive':
$data_array['harddrive'] = $item['HardDrive'];
break;
case 'RAM':
$data_array['ram'] = $item['RAM'];
break;
}
$data_array['qty'] = $item['qty'];
$data_array['rate' = number_format($item['rate'], 2, '.', '');
$data_array['rel_id'] = $insert_id;
$data_array['rel_type' = 'estimate';
$data_array['item_order'] = $item['order'];
$data_array['unit'] = $item['unit'];
$this->db->insert('tblitems_in', $data_array);

Categories