Home > OS >  laravel : How update a specific column with condition in controller?
laravel : How update a specific column with condition in controller?

Time:11-18

I'm blocked on this problem and I need your help to find a solution.

So I'm build a exam system in laravel but I want validate exam with condition. The conditions work but it updates all the rows related to the user's id. While I would like it to update only the line with related to the exam and user id to pass the result to 1.

In my controller I have this :

 if($note_theorique >= $eval->point_theorique && $note_pratique >= $eval->point_pratique && $tempspratique->temps <= $eval->temps_maximum){

                $resultatfinal = $stagiaire->resultatfinal;
                foreach($resultatfinal as $key => $resultat){
                    $result = $resultat->pivot;
                    $result->resultat = 1;
                    $result->save();
                }

            }

In my Stagiaire Model I have this relation :

public function resultatfinal(): BelongsToMany
    {
       return $this->belongsToMany(Evaluation::class, 'evaluation_pivot', 'stagiaire_id', 'eval_id')
       ->withPivot('resultat');
   }

in my database I have this :

Vue of database

So the problem is :

The stagiaire_id (User) number 5 pass the eval_id number 21 and met the conditions to have 1 in resultat column.

I don't know how but it change the second line and the third line to 1 instead of changing only the second line.

Do you have idea to resolve this?

Thanks.

CodePudding user response:

Have you tried with the sync() method?

// This should only set resultat = 1 on eval_id 21
$stagiaire->resultatfinal()->sync([21 => ['resultat' => 1], 26]);

https://laravel.com/docs/9.x/eloquent-relationships#syncing-associations

  • Related