Search code examples
phparrayslaravelexplodeimplode

getting trouble when updating specific column values in where I used php implode method is not updating properly


I have a table questions in where column answerid values are like 1,2,3,4,5,6,7,8,9,10 . Now I want to update questions table when I am going to delete an answer from answers table. Suppose, I am going to delete 5 number answer from answers table and also delete this 5 number from questions table. But when I am doing this questions table is updating like this- [{"answerid":"1,2,3,4,6,7,8,9,10"}] instead I want to update like 1,2,3,4,6,7,8,9,10 . I tried in my method like this-

public function deleteAnswer($id)
{
    $questionId = DB::table('answers')->where('id', $id)->get(['questionid']);
    $qid = $questionId[0]->questionid;
    $questionAns = DB::table('questions')->where('id', $qid)->get(['answerid']);

    $ansId = explode(",",$questionAns);
    //dd($ansId);


    while ($aid = current($ansId)) {
        if ($aid == $id) {
            $offset =  key($ansId);
        }
        next($ansId);
    }
   unset($ansId[$offset]);
    $implodeAnsIds = implode(",",$ansId);

   DB::table('questions')->where('id', $qid)->update([
        'answerid' => $implodeAnsIds,
   ]);

   return 'done';

}

Solution

  • The get() method on a query builder will always return a collection. However, you want a single property.

    A solution would be to pluck() the answerid column and select the first row. This will only select the property you need.

    $questionAns = DB::table('questions')->where('id', $qid)->pluck('answerid')->first();