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

afrasiyabhaider's avatar

How to Update Or Create - HasMany/BelongsTo (One to Many) relation

Please guide me on how to (update or create) student's previous academic record. I want to allow admin to add new academic record while updating the existing one as well that why I want to know about (createOrUpdate).

students Model

public function previous_academic_record()
    {
        return $this->hasMany(previous_academic_record::class);
    }


previous_academic_record Model

public function students()
    {
        return $this->belongsTo(students::class);
    }
0 likes
3 replies
mabdullahsari's avatar

Prepend and append your code snippet with three backticks so people have an easier time reading your snippet.

Snapey's avatar

createOrUpdate requires something to search for the student's record. If a model can be found with the search terms then the model is updated with the other fields. Otherwise a new record is created.

It is used where you don't know the ID for the record - because if you knew the ID then the record must exist and you can update it correctly.

But, no one can help you without an actual problem to be solved.

afrasiyabhaider's avatar

@mabdullahsari @snapey Here is my code..

for ($i = 0; $i < count($degree_name); $i++) {
            $user->teacher()->first()->teacher_qualification()->whereTeachersId($user->teacher()->first()->id)- 
            >updateOrCreate([
                'degree_name' => $degree_name[$i],
                'teachers_id' => $user->teacher()->first()->id,
                'board_university' => $board_university[$i],
                'degree_roll' => $degree_roll[$i],
                'passing_year' => (int) $passing_year[$i],
                'obtained_marks' => $obtained_marks[$i],
                'total_marks' => $total_marks[$i]
            ]);
        }

A teacher have multiple previous qualifications it is one to many relationship. User can

  • add teacher's one more previous qualifications
  • only update already saved record
  • delete one record while updating

So please suggest me what should i use in this case?

Please or to participate in this conversation.