Home:ALL Converter>How to update multiple rows in sql from array data using laravel eloquent

How to update multiple rows in sql from array data using laravel eloquent

Ask Time:2018-02-12T19:14:26         Author:Metono

Json Formatter

I was trying to update multiple records in my database using laravel eloquent but is getting errors when trying to update using an array.

I am not really sure how to correctly get the data from the array to my update function.

The array I am passing looks like this.

enter image description here

My Database table looks like

id | checklistid | categoryid | isCheck | created_at | updated_at

My Controller looks like this.

public function updateCategoryListData(Request $request){
    $checklistdata = $request->get('checklist');
    $id = $request->get('checklistid');
    $dataset = [] ;
    foreach($checklistdata as $key =>$value){
                $dataset[] = ['checklistid'=>$id,'categoryid' => $key,'isCheck'=>$value];
           }
        categorylistcontent::where([['checklistid',$id], ['categoryid', $dataset=>['categoryid'] ]])
            ->update($dataset['isCheck']);
}

Would you be able to advise how I can use the array to get the 'checklistid' and 'categoryid' to be used as the where clause of the update statement and then the 'isCheck' to be set in the update.

Author:Metono,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/48745122/how-to-update-multiple-rows-in-sql-from-array-data-using-laravel-eloquent
Sohel0415 :

You don't need dataset array, rather do the following:\n\nforeach($checklistdata as $key =>$value){\n categorylistcontent::where('checklistid',$id)->where('categoryid',$key)\n ->update(['isCheck'=>$value]);\n}\n",
2018-02-12T11:21:42
Alexey Mezenin :

You can't do that with just one query, but you could do that with two queries. An example:\n\n$check = categorylistcontent::query();\n$notCheck = categorylistcontent::query();\n\nforeach ($request->checklist as $item) {\n $query = $item['isCheck'] === 1 ? 'check' : 'notCheck';\n $$query->orWhere(function($q) use($item) {\n $q->where('checklistid', $item['checklistid'])->where('categoryid', $item['categoryid']);\n }\n}\n\n$check->update(['check' => 1]);\n$notCheck->update(['check' => 1]);\n\n\nI haven't tested this exact code, but I think it will be helpful for you to get the idea.",
2018-02-12T11:26:24
yy