|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Backpack\CRUD\app\Library\CrudPanel\Traits; |
|
4
|
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Model; |
|
6
|
|
|
use Illuminate\Database\Eloquent\Relations\BelongsToMany; |
|
7
|
|
|
use Illuminate\Database\Eloquent\Relations\MorphToMany; |
|
8
|
|
|
use Illuminate\Support\Arr; |
|
9
|
|
|
use Illuminate\Support\Facades\DB; |
|
10
|
|
|
|
|
11
|
|
|
trait Create |
|
12
|
|
|
{ |
|
13
|
|
|
/* |
|
14
|
|
|
|-------------------------------------------------------------------------- |
|
15
|
|
|
| CREATE |
|
16
|
|
|
|-------------------------------------------------------------------------- |
|
17
|
|
|
*/ |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* Insert a row in the database. |
|
21
|
|
|
* |
|
22
|
|
|
* @param array $input All input values to be inserted. |
|
23
|
|
|
* @return Model |
|
24
|
|
|
*/ |
|
25
|
|
|
public function create($input) |
|
26
|
|
|
{ |
|
27
|
|
|
[$directInputs, $relationInputs] = $this->splitInputIntoDirectAndRelations($input); |
|
|
|
|
|
|
28
|
|
|
|
|
29
|
|
|
if ($this->get('create.useDatabaseTransactions') ?? config('backpack.base.useDatabaseTransactions', false)) { |
|
|
|
|
|
|
30
|
|
|
return DB::transaction(fn () => $this->createModelAndRelations($directInputs, $relationInputs)); |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
return $this->createModelAndRelations($directInputs, $relationInputs); |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
private function createModelAndRelations(array $directInputs, array $relationInputs): Model |
|
37
|
|
|
{ |
|
38
|
|
|
$item = $this->model->create($directInputs); |
|
39
|
|
|
$this->createRelationsForItem($item, $relationInputs); |
|
40
|
|
|
|
|
41
|
|
|
return $item; |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
/** |
|
45
|
|
|
* Get all fields needed for the ADD NEW ENTRY form. |
|
46
|
|
|
* |
|
47
|
|
|
* @return array The fields with attributes and fake attributes. |
|
48
|
|
|
*/ |
|
49
|
|
|
public function getCreateFields() |
|
50
|
|
|
{ |
|
51
|
|
|
return $this->fields(); |
|
|
|
|
|
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
/** |
|
55
|
|
|
* Get all fields with relation set (model key set on field). |
|
56
|
|
|
* |
|
57
|
|
|
* @param array $fields |
|
58
|
|
|
* @return array The fields with model key set. |
|
59
|
|
|
*/ |
|
60
|
|
|
public function getRelationFields($fields = []) |
|
61
|
|
|
{ |
|
62
|
|
|
if (empty($fields)) { |
|
63
|
|
|
$fields = $this->getCleanStateFields(); |
|
|
|
|
|
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
$relationFields = []; |
|
67
|
|
|
|
|
68
|
|
|
foreach ($fields as $field) { |
|
69
|
|
|
if (isset($field['model']) && $field['model'] !== false && $field['entity'] !== false) { |
|
70
|
|
|
array_push($relationFields, $field); |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
// if a field has an array name AND subfields |
|
74
|
|
|
// then take those fields into account (check if they have relationships); |
|
75
|
|
|
// this is done in particular for the checklist_dependency field, |
|
76
|
|
|
// but other fields could use it too, in the future; |
|
77
|
|
|
if ($this->holdsMultipleInputs($field['name']) && |
|
|
|
|
|
|
78
|
|
|
isset($field['subfields']) && |
|
79
|
|
|
is_array($field['subfields'])) { |
|
80
|
|
|
foreach ($field['subfields'] as $subfield) { |
|
81
|
|
|
if (isset($subfield['model']) && $subfield['model'] !== false) { |
|
82
|
|
|
array_push($relationFields, $subfield); |
|
83
|
|
|
} |
|
84
|
|
|
} |
|
85
|
|
|
} |
|
86
|
|
|
} |
|
87
|
|
|
|
|
88
|
|
|
return $relationFields; |
|
89
|
|
|
} |
|
90
|
|
|
|
|
91
|
|
|
/** |
|
92
|
|
|
* --------------- |
|
93
|
|
|
* PRIVATE METHODS |
|
94
|
|
|
* ---------------. |
|
95
|
|
|
*/ |
|
96
|
|
|
|
|
97
|
|
|
/** |
|
98
|
|
|
* Create relations for the provided model. |
|
99
|
|
|
* |
|
100
|
|
|
* @param Model $item The current CRUD model. |
|
101
|
|
|
* @param array $formattedRelations The form data. |
|
102
|
|
|
* @return bool|null |
|
103
|
|
|
*/ |
|
104
|
|
|
private function createRelationsForItem($item, $formattedRelations) |
|
105
|
|
|
{ |
|
106
|
|
|
// no relations to create |
|
107
|
|
|
if (empty($formattedRelations)) { |
|
108
|
|
|
return false; |
|
109
|
|
|
} |
|
110
|
|
|
|
|
111
|
|
|
foreach ($formattedRelations as $relationMethod => $relationDetails) { |
|
112
|
|
|
$relation = $item->{$relationMethod}(); |
|
113
|
|
|
$relationType = $relationDetails['relation_type']; |
|
114
|
|
|
|
|
115
|
|
|
switch ($relationType) { |
|
116
|
|
|
case 'HasOne': |
|
117
|
|
|
case 'MorphOne': |
|
118
|
|
|
$this->createUpdateOrDeleteOneToOneRelation($relation, $relationMethod, $relationDetails); |
|
119
|
|
|
break; |
|
120
|
|
|
case 'HasMany': |
|
121
|
|
|
case 'MorphMany': |
|
122
|
|
|
$relationValues = $relationDetails['values'][$relationMethod]; |
|
123
|
|
|
// if relation values are null we can only attach, also we check if we sent |
|
124
|
|
|
// - a single dimensional array: [1,2,3] |
|
125
|
|
|
// - an array of arrays: [[1][2][3]] |
|
126
|
|
|
// if is as single dimensional array we can only attach. |
|
127
|
|
|
if ($relationValues === null || ! is_multidimensional_array($relationValues)) { |
|
128
|
|
|
$this->attachManyRelation($item, $relation, $relationDetails, $relationValues); |
|
129
|
|
|
} else { |
|
130
|
|
|
$this->createManyEntries($item, $relation, $relationMethod, $relationDetails); |
|
131
|
|
|
} |
|
132
|
|
|
break; |
|
133
|
|
|
case 'BelongsToMany': |
|
134
|
|
|
case 'MorphToMany': |
|
135
|
|
|
$values = $relationDetails['values'][$relationMethod] ?? []; |
|
136
|
|
|
$values = is_string($values) ? (json_decode($values, true) ?? []) : $values; |
|
137
|
|
|
$field = $relationDetails['crudFields'][0] ?? []; |
|
138
|
|
|
|
|
139
|
|
|
// if the values are multidimensional, we have additional pivot data. |
|
140
|
|
|
if (is_array($values) && is_multidimensional_array($values)) { |
|
141
|
|
|
// if the field allow duplicated pivots, we can't use sync or attach from laravel, we need to manually handle the pivot data. |
|
142
|
|
|
if ($field['allow_duplicate_pivots'] ?? false) { |
|
143
|
|
|
$keyName = $field['pivot_key_name'] ?? 'id'; |
|
144
|
|
|
$sentIds = array_filter(array_column($values, $keyName)); |
|
145
|
|
|
$dbValues = $relation->newPivotQuery()->pluck($keyName)->toArray(); |
|
146
|
|
|
|
|
147
|
|
|
$toDelete = array_diff($dbValues, $sentIds); |
|
148
|
|
|
|
|
149
|
|
|
if (! empty($toDelete)) { |
|
150
|
|
|
foreach ($toDelete as $id) { |
|
151
|
|
|
$relation->newPivot()->where($keyName, $id)->delete(); |
|
152
|
|
|
} |
|
153
|
|
|
} |
|
154
|
|
|
foreach ($values as $value) { |
|
155
|
|
|
// if it's an existing pivot, update it |
|
156
|
|
|
$attributes = $this->preparePivotAttributesForSave($value, $relation, $item->getKey(), $keyName); |
|
157
|
|
|
if (isset($value[$keyName])) { |
|
158
|
|
|
$relation->newPivot()->where($keyName, $value[$keyName])->update($attributes); |
|
159
|
|
|
} else { |
|
160
|
|
|
$relation->newPivot()->create($attributes); |
|
161
|
|
|
} |
|
162
|
|
|
} |
|
163
|
|
|
break; |
|
164
|
|
|
} |
|
165
|
|
|
|
|
166
|
|
|
$relationToManyValues = []; |
|
167
|
|
|
|
|
168
|
|
|
foreach ($values as $value) { |
|
169
|
|
|
if (isset($value[$relationMethod])) { |
|
170
|
|
|
$relationToManyValues[$value[$relationMethod]] = Arr::except($value, $relationMethod); |
|
171
|
|
|
} |
|
172
|
|
|
} |
|
173
|
|
|
|
|
174
|
|
|
$item->{$relationMethod}()->sync($relationToManyValues); |
|
175
|
|
|
unset($relationToManyValues); |
|
176
|
|
|
break; |
|
177
|
|
|
} |
|
178
|
|
|
|
|
179
|
|
|
// if there is no relation data, and the values array is single dimensional we have |
|
180
|
|
|
// an array of keys with no additional pivot data. sync those. |
|
181
|
|
|
if (empty($relationToManyValues)) { |
|
182
|
|
|
$relationToManyValues = array_values($values); |
|
183
|
|
|
} |
|
184
|
|
|
$item->{$relationMethod}()->sync($relationToManyValues); |
|
185
|
|
|
unset($relationToManyValues); |
|
186
|
|
|
break; |
|
187
|
|
|
} |
|
188
|
|
|
} |
|
189
|
|
|
} |
|
190
|
|
|
|
|
191
|
|
|
private function preparePivotAttributesForSave(array $attributes, BelongsToMany|MorphToMany $relation, string|int $relatedItemKey, $pivotKeyName) |
|
192
|
|
|
{ |
|
193
|
|
|
$attributes[$relation->getForeignPivotKeyName()] = $relatedItemKey; |
|
194
|
|
|
$attributes[$relation->getRelatedPivotKeyName()] = $attributes[$relation->getRelationName()]; |
|
195
|
|
|
|
|
196
|
|
|
if ($relation instanceof MorphToMany) { |
|
197
|
|
|
$attributes[$relation->getMorphType()] = $relation->getMorphClass(); |
|
198
|
|
|
} |
|
199
|
|
|
|
|
200
|
|
|
return Arr::except($attributes, [$relation->getRelationName(), $pivotKeyName]); |
|
201
|
|
|
} |
|
202
|
|
|
|
|
203
|
|
|
/** |
|
204
|
|
|
* Save the attributes of a given HasOne or MorphOne relationship on the |
|
205
|
|
|
* related entry, create or delete it, depending on what was sent in the form. |
|
206
|
|
|
* |
|
207
|
|
|
* For HasOne and MorphOne relationships, the dev might want to a few different things: |
|
208
|
|
|
* (A) save an attribute on the related entry (eg. passport.number) |
|
209
|
|
|
* (B) set an attribute on the related entry to NULL (eg. slug.slug) |
|
210
|
|
|
* (C) save an entire related entry (eg. passport) |
|
211
|
|
|
* (D) delete the entire related entry (eg. passport) |
|
212
|
|
|
* |
|
213
|
|
|
* @param \Illuminate\Database\Eloquent\Relations\HasOne|\Illuminate\Database\Eloquent\Relations\MorphOne $relation |
|
214
|
|
|
* @param string $relationMethod The name of the relationship method on the main Model. |
|
215
|
|
|
* @param array $relationDetails Details about that relationship. For example: |
|
216
|
|
|
* [ |
|
217
|
|
|
* 'model' => 'App\Models\Passport', |
|
218
|
|
|
* 'parent' => 'App\Models\Pet', |
|
219
|
|
|
* 'entity' => 'passport', |
|
220
|
|
|
* 'attribute' => 'passport', |
|
221
|
|
|
* 'values' => **THE TRICKY BIT**, |
|
222
|
|
|
* ] |
|
223
|
|
|
* @return Model|null |
|
224
|
|
|
*/ |
|
225
|
|
|
private function createUpdateOrDeleteOneToOneRelation($relation, $relationMethod, $relationDetails) |
|
226
|
|
|
{ |
|
227
|
|
|
// Let's see which scenario we're treating, depending on the contents of $relationDetails: |
|
228
|
|
|
// - (A) ['number' => 1315, 'name' => 'Something'] (if passed using a text/number/etc field) |
|
229
|
|
|
// - (B) ['slug' => null] (if the 'slug' attribute on the 'slug' related entry needs to be cleared) |
|
230
|
|
|
// - (C) ['passport' => [['number' => 1314, 'name' => 'Something']]] (if passed using a repeatable field) |
|
231
|
|
|
// - (D) ['passport' => null] (if deleted from the repeatable field) |
|
232
|
|
|
|
|
233
|
|
|
// Scenario C or D |
|
234
|
|
|
if (array_key_exists($relationMethod, $relationDetails['values'])) { |
|
235
|
|
|
$relationMethodValue = $relationDetails['values'][$relationMethod]; |
|
236
|
|
|
|
|
237
|
|
|
// Scenario D |
|
238
|
|
|
if (is_null($relationMethodValue) && $relationDetails['entity'] === $relationMethod) { |
|
239
|
|
|
$relation->first()?->delete(); |
|
240
|
|
|
|
|
241
|
|
|
return null; |
|
242
|
|
|
} |
|
243
|
|
|
|
|
244
|
|
|
// Scenario C (when it's an array inside an array, because it's been added as one item inside a repeatable field) |
|
245
|
|
|
if (gettype($relationMethodValue) == 'array' && is_multidimensional_array($relationMethodValue)) { |
|
246
|
|
|
$relationMethodValue = $relationMethodValue[0]; |
|
247
|
|
|
} |
|
248
|
|
|
} |
|
249
|
|
|
// saving process |
|
250
|
|
|
$input = $relationMethodValue ?? $relationDetails['values']; |
|
251
|
|
|
[$directInputs, $relationInputs] = $this->splitInputIntoDirectAndRelations($input, $relationDetails, $relationMethod); |
|
252
|
|
|
|
|
253
|
|
|
$item = $relation->updateOrCreate([], $directInputs); |
|
254
|
|
|
|
|
255
|
|
|
$this->createRelationsForItem($item, $relationInputs); |
|
256
|
|
|
|
|
257
|
|
|
return $item; |
|
258
|
|
|
} |
|
259
|
|
|
|
|
260
|
|
|
/** |
|
261
|
|
|
* When using the HasMany/MorphMany relations as selectable elements we use this function to "mimic-sync" in those relations. |
|
262
|
|
|
* Since HasMany/MorphMany does not have the `sync` method, we manually re-create it. |
|
263
|
|
|
* Here we add the entries that developer added and remove the ones that are not in the list. |
|
264
|
|
|
* This removal process happens with the following rules: |
|
265
|
|
|
* - by default Backpack will behave like a `sync` from M-M relations: it deletes previous entries and add only the current ones. |
|
266
|
|
|
* - `force_delete` is configurable in the field, it's `true` by default. When false, if connecting column is nullable instead of deleting the row we set the column to null. |
|
267
|
|
|
* - `fallback_id` could be provided. In this case instead of deleting we set the connecting key to whatever developer gives us. |
|
268
|
|
|
* |
|
269
|
|
|
* @return mixed |
|
270
|
|
|
*/ |
|
271
|
|
|
private function attachManyRelation($item, $relation, $relationDetails, $relationValues) |
|
272
|
|
|
{ |
|
273
|
|
|
$modelInstance = $relation->getRelated(); |
|
274
|
|
|
$relationForeignKey = $relation->getForeignKeyName(); |
|
275
|
|
|
$relationLocalKey = $relation->getLocalKeyName(); |
|
276
|
|
|
|
|
277
|
|
|
if (empty($relationValues)) { |
|
278
|
|
|
// the developer cleared the selection |
|
279
|
|
|
// we gonna clear all related values by setting up the value to the fallback id, to null or delete. |
|
280
|
|
|
return $this->handleManyRelationItemRemoval($modelInstance, $relation, $relationDetails, $relationForeignKey); |
|
281
|
|
|
} |
|
282
|
|
|
// we add the new values into the relation, if it is HasMany we only update the foreign_key, |
|
283
|
|
|
// otherwise (it's a MorphMany) we need to update the morphs keys too |
|
284
|
|
|
$toUpdate[$relationForeignKey] = $item->{$relationLocalKey}; |
|
|
|
|
|
|
285
|
|
|
|
|
286
|
|
|
if ($relationDetails['relation_type'] === 'MorphMany') { |
|
287
|
|
|
$toUpdate[$relation->getQualifiedMorphType()] = $relation->getMorphClass(); |
|
288
|
|
|
} |
|
289
|
|
|
|
|
290
|
|
|
$modelInstance->whereIn($modelInstance->getKeyName(), $relationValues) |
|
291
|
|
|
->update($toUpdate); |
|
292
|
|
|
|
|
293
|
|
|
// we clear up any values that were removed from model relation. |
|
294
|
|
|
// if developer provided a fallback id, we use it |
|
295
|
|
|
// if column is nullable we set it to null if developer didn't specify `force_delete => true` |
|
296
|
|
|
// if none of the above we delete the model from database |
|
297
|
|
|
$removedEntries = $modelInstance->whereNotIn($modelInstance->getKeyName(), $relationValues) |
|
298
|
|
|
->where($relationForeignKey, $item->{$relationLocalKey}); |
|
299
|
|
|
|
|
300
|
|
|
// if relation is MorphMany we also match by morph type. |
|
301
|
|
|
if ($relationDetails['relation_type'] === 'MorphMany') { |
|
302
|
|
|
$removedEntries->where($relation->getQualifiedMorphType(), $relation->getMorphClass()); |
|
303
|
|
|
} |
|
304
|
|
|
|
|
305
|
|
|
return $this->handleManyRelationItemRemoval($modelInstance, $removedEntries, $relationDetails, $relationForeignKey); |
|
306
|
|
|
} |
|
307
|
|
|
|
|
308
|
|
|
private function handleManyRelationItemRemoval($modelInstance, $removedEntries, $relationDetails, $relationForeignKey) |
|
309
|
|
|
{ |
|
310
|
|
|
$relationColumnIsNullable = $modelInstance->isColumnNullable($relationForeignKey); |
|
311
|
|
|
$forceDelete = $relationDetails['force_delete'] ?? false; |
|
312
|
|
|
$fallbackId = $relationDetails['fallback_id'] ?? false; |
|
313
|
|
|
|
|
314
|
|
|
// developer provided a fallback_id he knows what he's doing, just use it. |
|
315
|
|
|
if ($fallbackId) { |
|
316
|
|
|
return $removedEntries->update([$relationForeignKey => $fallbackId]); |
|
317
|
|
|
} |
|
318
|
|
|
|
|
319
|
|
|
// developer set force_delete => true, so we don't care if it's nullable or not, |
|
320
|
|
|
// we just follow developer's will |
|
321
|
|
|
if ($forceDelete) { |
|
322
|
|
|
return $removedEntries->lazy()->each->delete(); |
|
323
|
|
|
} |
|
324
|
|
|
|
|
325
|
|
|
// get the default that could be set at database level. |
|
326
|
|
|
$dbColumnDefault = $modelInstance->getDbColumnDefault($relationForeignKey); |
|
327
|
|
|
|
|
328
|
|
|
// check if the relation foreign key is in casts, and cast it to the correct type |
|
329
|
|
|
if ($modelInstance->hasCast($relationForeignKey)) { |
|
330
|
|
|
$dbColumnDefault = match ($modelInstance->getCasts()[$relationForeignKey]) { |
|
331
|
|
|
'int', 'integer' => $dbColumnDefault = (int) $dbColumnDefault, |
|
332
|
|
|
default => $dbColumnDefault = $dbColumnDefault |
|
|
|
|
|
|
333
|
|
|
}; |
|
334
|
|
|
} |
|
335
|
|
|
// if column is not nullable in database, and there is no column default (null), |
|
336
|
|
|
// we will delete the entry from the database, otherwise it will throw and ugly DB error. |
|
337
|
|
|
if (! $relationColumnIsNullable && $dbColumnDefault === null) { |
|
338
|
|
|
return $removedEntries->lazy()->each->delete(); |
|
339
|
|
|
} |
|
340
|
|
|
|
|
341
|
|
|
// if column is nullable we just set it to the column default (null when it does exist, or the default value when it does). |
|
342
|
|
|
return $removedEntries->update([$relationForeignKey => $dbColumnDefault]); |
|
343
|
|
|
} |
|
344
|
|
|
|
|
345
|
|
|
/** |
|
346
|
|
|
* Handle HasMany/MorphMany relations when used as creatable entries in the crud. |
|
347
|
|
|
* By using repeatable field, developer can allow the creation of such entries |
|
348
|
|
|
* in the crud forms. |
|
349
|
|
|
* |
|
350
|
|
|
* @param $entry - eg: story |
|
|
|
|
|
|
351
|
|
|
* @param $relation - eg story HasMany monsters |
|
352
|
|
|
* @param $relationMethod - eg: monsters |
|
353
|
|
|
* @param $relationDetails - eg: info about relation including submitted values |
|
354
|
|
|
* @return void |
|
355
|
|
|
*/ |
|
356
|
|
|
private function createManyEntries($entry, $relation, $relationMethod, $relationDetails) |
|
357
|
|
|
{ |
|
358
|
|
|
$items = $relationDetails['values'][$relationMethod]; |
|
359
|
|
|
|
|
360
|
|
|
$relatedModelLocalKey = $relation->getRelated()->getKeyName(); |
|
361
|
|
|
|
|
362
|
|
|
$relatedItemsSent = []; |
|
363
|
|
|
|
|
364
|
|
|
foreach ($items as $item) { |
|
365
|
|
|
[$directInputs, $relationInputs] = $this->splitInputIntoDirectAndRelations($item, $relationDetails, $relationMethod); |
|
366
|
|
|
// for each item we get the inputs to create and the relations of it. |
|
367
|
|
|
$relatedModelLocalKeyValue = $item[$relatedModelLocalKey] ?? null; |
|
368
|
|
|
|
|
369
|
|
|
// we either find the matched entry by local_key (usually `id`) |
|
370
|
|
|
// and update the values from the input |
|
371
|
|
|
// or create a new item from input |
|
372
|
|
|
$item = $entry->{$relationMethod}()->updateOrCreate([$relatedModelLocalKey => $relatedModelLocalKeyValue], $directInputs); |
|
373
|
|
|
|
|
374
|
|
|
// we store the item local key so we can match them with database and check if any item was deleted |
|
375
|
|
|
$relatedItemsSent[] = $item->{$relatedModelLocalKey}; |
|
376
|
|
|
|
|
377
|
|
|
// create the item relations if any. |
|
378
|
|
|
$this->createRelationsForItem($item, $relationInputs); |
|
379
|
|
|
} |
|
380
|
|
|
|
|
381
|
|
|
// use the collection of sent ids to match against database ids, delete the ones not found in the submitted ids. |
|
382
|
|
|
if (! empty($relatedItemsSent)) { |
|
383
|
|
|
// we perform the cleanup of removed database items |
|
384
|
|
|
$entry->{$relationMethod}()->whereNotIn($relatedModelLocalKey, $relatedItemsSent)->lazy()->each->delete(); |
|
385
|
|
|
} |
|
386
|
|
|
} |
|
387
|
|
|
} |
|
388
|
|
|
|