Skip to content
Advertisement

Laravel update model’s one-to-many relation’s items

I have two Eloquent models:

JavaScript
JavaScript

Item‘s columns are id, userId and name.

When I want to update the user (PUT /users/<id>) I also want to update the items in the same request, meaning:

  1. Skip existing items
  2. Add new items
  3. Remove extra items

Afterwards both DB and the relation should have up-to-date items.

Example of the request data:

JavaScript

I tried to look for a simple way to do this with Laravel, for example with many-to-many relations you can just call attach/detach and sync to automatically update them with ids.

I have made this abomination for my one-to-many relation:

JavaScript

This user + items model is just an example – I have multiple similar relations (where there is more than just name column) and copy pasting this code everywhere and slightly modifying it seems a little bit dumb.

Laravel is known for all these fancy shortcuts and easy to use/magic methods so my question here is: is there a simpler and shorter way to do this update?

Advertisement

Answer

You can use Laravel collections.

First, update the user:

JavaScript

Then, you can sync user items:

JavaScript

For models with more than one field, you need to pass two arrays to the firstOrCreate method. The first array will be used to find the model, and, if not found, it will be created with the merge of the two arrays:

JavaScript

Since you are using firstOrCreate, it will only create the item if it’s not found by it’s name, and you will not have duplicated items.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement