Update, create and delete hasMany() relations in one go

Posted 1 year ago by davestewart

Is it possible to pass an array to Eloquent and have it update, create or delete relations in one shot?

My usage: a SPA and a user has many addresses:

  • let's say he has addresses 1 and 2, and these are downloaded to the app.
  • in the app, the user deletes 1, amends 2, and adds a 3rd.
  • we now have addresses 2 and 3

When I upload to the server, I want to do a diff on existing addresses, and take action accordingly:

  • delete address 1
  • update address 2
  • create address 3

Is there a built-in way to do this?

The other approach I suppose would be to do this one at a time, but in my case, I want the user to be able to update various forms in sequence, then only at the end submit data.

So ideally I'd have something like:

$user->updateRelations($arr)

But happy to do it all manually.

Cheers, Dave

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

Laracasts Mascot

Hi, Have We Met Yet?

Did you know that, in addition to the forum, Laracasts includes well over 1000 lessons on modern web development? All for the price of one lunch out per month.

Sign Me Up

Channels

Reply to

Use Markdown with GitHub-flavored code blocks.