0

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

  1. $request->dataWeight This variable is coming from ajax request that contains something like this 95,75,65 a value that is separated by commas.

  2. $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?

2
  • You want to update taskWeight related to taskCode? Commented Nov 5, 2019 at 7:25
  • yes I want to update taskWeight where taskCode is given from the $request->dataWeightAttr Commented Nov 5, 2019 at 7:27

2 Answers 2

1

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()
    ]);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.