@@ -19,6 +19,14 @@ trait HasNestedAttributesTrait
1919 */
2020 protected $ acceptNestedAttributesFor = [];
2121
22+ /**
23+ * Defined "destroy" key name
24+ *
25+ * @var string
26+ */
27+ protected $ destroyNestedKey = '_destroy ' ;
28+
29+
2230 /**
2331 * Get accept nested attributes
2432 *
@@ -80,7 +88,7 @@ public function save(array $options = [])
8088 }
8189 } else if ($ relation instanceof HasMany || $ relation instanceof MorphMany) {
8290 foreach ($ stack as $ params ) {
83- if (!$ this ->saveManyNestedAttributes ($ relation , $ params )) {
91+ if (!$ this ->saveManyNestedAttributes ($ this -> $ methodName () , $ params )) {
8492 return false ;
8593 }
8694 }
@@ -103,6 +111,9 @@ public function save(array $options = [])
103111 protected function saveNestedAttributes ($ relation , array $ params )
104112 {
105113 if ($ this ->exists && $ model = $ relation ->first ()) {
114+ if ($ this ->allowDestroyNestedAttributes ($ params )) {
115+ return $ model ->delete ();
116+ }
106117 return $ model ->update ($ stack );
107118 } else if ($ relation ->create ($ stack )) {
108119 return true ;
@@ -121,10 +132,25 @@ protected function saveManyNestedAttributes($relation, array $params)
121132 {
122133 if (isset ($ params ['id ' ]) && $ this ->exists ) {
123134 $ model = $ relation ->findOrFail ($ params ['id ' ]);
135+
136+ if ($ this ->allowDestroyNestedAttributes ($ params )) {
137+ return $ model ->delete ();
138+ }
124139 return $ model ->update ($ params );
125140 } else if ($ relation ->create ($ params )) {
126141 return true ;
127142 }
128143 return false ;
129144 }
145+
146+ /**
147+ * Check can we delete nested data
148+ *
149+ * @param array $params
150+ * @return bool
151+ */
152+ protected function allowDestroyNestedAttributes (array $ params )
153+ {
154+ return isset ($ params [$ this ->destroyNestedKey ]) && (bool ) $ params [$ this ->destroyNestedKey ] == true ;
155+ }
130156}
0 commit comments