Skip to content

Commit 25ebe96

Browse files
author
Piotr Krajewski
committed
fix
1 parent eca7481 commit 25ebe96

File tree

2 files changed

+23
-10
lines changed

2 files changed

+23
-10
lines changed

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
"keywords": [
66
"Laravel", "Lumen", "Eloquent", "Nested Attributes"
77
],
8-
"version": "0.0.3",
8+
"version": "0.0.4",
99
"homepage": "https://github.com/mits87/eloquent-nested-attributes",
1010
"license": "MIT",
1111
"authors": [

src/Traits/HasNestedAttributesTrait.php

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -73,14 +73,14 @@ public function save(array $options = [])
7373
}
7474

7575
$relation = $this->$methodName();
76-
76+
7777
if ($relation instanceof HasOne || $relation instanceof MorphOne) {
7878
if (!$this->saveNestedAttributes($relation, $stack)) {
7979
return false;
8080
}
8181
} else if ($relation instanceof HasMany || $relation instanceof MorphMany) {
8282
foreach ($stack as $params) {
83-
if (!$this->saveNestedAttributes($relation, $params)) {
83+
if (!$this->saveManyNestedAttributes($relation, $params)) {
8484
return false;
8585
}
8686
}
@@ -94,20 +94,33 @@ public function save(array $options = [])
9494
}
9595

9696
/**
97-
* Save the nested relation attributes to the database.
97+
* Save the hasOne nested relation attributes to the database.
9898
*
9999
* @param Illuminate\Database\Eloquent\Relations $relation
100100
* @param array $params
101101
* @return bool
102102
*/
103103
protected function saveNestedAttributes($relation, array $params)
104104
{
105-
if ($this->exists) {
106-
if (isset($params['id'])) {
107-
$model = $relation->findOrFail($params['id']);
108-
} else {
109-
$model = $relation->firstOrFail();
110-
}
105+
if ($this->exists && $model = $relation->first()) {
106+
return $model->update($stack);
107+
} else if ($relation->create($stack)) {
108+
return true;
109+
}
110+
return false;
111+
}
112+
113+
/**
114+
* Save the hasMany nested relation attributes to the database.
115+
*
116+
* @param Illuminate\Database\Eloquent\Relations $relation
117+
* @param array $params
118+
* @return bool
119+
*/
120+
protected function saveManyNestedAttributes($relation, array $params)
121+
{
122+
if (isset($params['id']) && $this->exists) {
123+
$model = $relation->findOrFail($params['id']);
111124
return $model->update($params);
112125
} else if ($relation->create($params)) {
113126
return true;

0 commit comments

Comments
 (0)