bart

Update one-to-many relation

Posted 1 year ago by bart

Hey everyone,

I'm currently struggling a bit with a one-to-many relation in Eloquent. I'm trying to update children that are related to a parent. I'll give you an example:

Table 1: users (with id and username) Table 2: awards (with user_id, year, award_type)

One user can have many awards which is associated in the user class by:

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

Now when updating the user I'm getting back an array of awards from the frontend like this:

$awards = [
    ['year' => 2016, 'award_type' => 1],
    ['year' => 2017, 'award_type' => 2],
    ['year' => 2018, 'award_type' => 1]
];

What I tried now was something like calling sync() and save() on $user->awards() but that does only work for many-to-many relations. I'm having a one-to-many relation instead so my current workaround in the controllers update method looks like this. It feels a bit weird so I'm curious if you have a better approach for it?

$user->awards()->delete();
foreach($request->awards as $award) {
    $award['user_id'] = $user->id;
    Award::create($award);
}

Thank you very much!

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.