Wednesday, March 8, 2017

Laravel 5.x Eloquent method to update, create or delete dynamic input

I have a dynamic form element (say names of book titles) that a user can add or delete in the view. Creation is a breeze because all book models are new when the request arrives in the controller for saving to the database. During updating, if all book models are just left the same, modified or new ones are added, I can do the task with updateOrCreate where all three cases are satisfied.

The problem now is when the user chooses to remove a book in the view; Laravel tries to save the deleted model:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'column_name' cannot be null

Is there an updateCreateOrDelete method or similar for this? I do not want to delete all books in the DB and re-create them because that is lazy and not recommended if the system has an audit system.

Basically I have an array of inputs that can be added or deleted:

  1. if anything is updated then just update their DB entry;
  2. if n are added, then create these new n values;
  3. if m are deleted, then delete these m values from the DB


via Saggy Manatee And Swan Folk

Advertisement