I have two Eloquent models:
class User extends Model { public function items() { returnthis->belongsTo(User::class, "userId"); } }
Item
id
userId
name
When I want to update the user (
PUT /users/<id>
- Skip existing items
- Add new items
- Remove extra items
Afterwards both DB and the relation should have up-to-date items.
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
sync
I have made this abomination for my one-to-many relation:
// Controller method for PUT /users/<id> public function update(Userrequest) { // Update user attributes normal way
request->validated());
newItems =
currentItems =
removeItemIds = []; foreach (
i =>
exists = false; foreach (
j =>
currentItem->name ===
exists = true; break; } } if (
newItems[
removeItemIds[] =
currentItems[
newItems as
item = Item::make(
item->userId =
item->save();
item); } // Delete extra items
removeItemIds)->delete(); // Update relation so the returned data is up-to-date as well
currentItems); return [ "user" => new UserResource($user), ]; }
This user + items model is just an example – I have multiple similar relations (where there is more than just
name
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?
Anonymous Asked question May 13, 2021
Recent Comments