Reputation: 510
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?
Upvotes: 0
Views: 65
Reputation: 5731
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()
]);
}
Upvotes: 1
Reputation: 1932
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()
]);
Upvotes: 1