Having an issue updating multiple records at once. Only the first record is getting updated while the rest are not.
Using the fetch API for AJAX calls and sending array data successfully, as confirmed in the browser's dev tools.
When attempting to save them in a foreach loop, only the first record gets updated.
In controller:
public function approveComment(Request $request)
{
if ($request->ajax()) {
$ids = $request->json()->all();
foreach ($ids as $id) {
$comment = Comments::find($id);
$comment->comment_status = 1;
$comment->save();
}
return response()->json("successful");
} else {
$comment = Comments::find($request->input('comment_id'));
$comment->comment_status = 1;
$comment->save();
return back();
}
}
AJAX call example:
ajax.put('comments/approve',token,ids)
.then(data => data.json())
.then(log => console.log(log))
.catch(err => console.log(err))
Definition of put method in AJAX class:
async put(url, token, data) {
const response = await fetch(url, {
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
"X-CSRF-Token": token
},
method: "put",
credentials: "same-origin",
body: JSON.stringify(data)
});
return response;
}