Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vandan's avatar
Level 13

how to update all option ?

i have two migrations quiz and option when i update a question and option but only update question and first option update in all three option are same value so how to update all option in particalur question

here is my controller file

public function question(Request $request,$id)
    {
        \DB::table('quiz')
                ->where('id','=',$id)
                ->update([
                'question' => $request->get('question'),               
        ]);

        $qid=quiz::where('id','=',$id)->get();
        $option=$request->get('option');
        foreach($option as $option)
        {
            \DB::table('opts')
                ->where('qid','=',$id)
                ->update([
                        'option'=> $options
                ]);
        }
        return back();
}

thanks

0 likes
5 replies
vandan's avatar
Level 13

sorry its my coding partner so its not find solution how to do it , and i also confused how to do it ?

i have two tables but i have four option in array but when i try to update options then only one option can update then other 3 option is same value update so please give some suggestion how to do it

vandan's avatar
Level 13

@yezawhein

here is my option table relationship

class Option extends Model
{
        protected $fillable=['qid','option'];
        public function quiz()
        {
                return $this->belongsTo('App\Quiz','qid');
        }
}

here is my quiz table relationship

class Quiz extends Model
{
        protected $table = 'quiz';
        protected $fillable = [
            'level_id','quiz','question_complexity','tie_breaker','marks','author'];

        public function options()
        {
                return $this->hasMany('App\Option');
        }
}

one quiz hasmany options & options belongs to quiz here

Snapey's avatar
Snapey
Best Answer
Level 122

consider this

     foreach($option as $option)
        {
            \DB::table('opts')
                ->where('qid','=',$id)
                ->update([
                        'option'=> $options
                ]);
        }

You say you have four options. All options with have the same qid

Each time around the loop, you are telling your database to set all options with that qid with $data. As there are four records that match that where statement then they all get updated.

Next time around the loop again, you update the same four records, etc

Your choice is either

a) delete all the options first and use insert in your loop

b) give each option an id and keep trackof this in your front end. You can then update specific option id

1 like

Please or to participate in this conversation.