diff --git a/readme.md b/readme.md index 73decef..349fdb8 100644 --- a/readme.md +++ b/readme.md @@ -33,6 +33,14 @@ You can explicitly define the relationship & Nova resource: AttachMany::make('Field Name', 'relationshipName', RelatedResource::class); ``` +### Pivot Values +You can pass additional parameters for any pivot value. +For details, please check https://laravel.com/docs/9.x/eloquent-relationships#syncing-associations + +```php +AttachMany::make('Field Name', 'relationshipName', RelatedResource::class, ['pivot_name' => value]); +``` + ### Display on detail: This package only provides the create / edit views that BelongsToMany does not. diff --git a/src/AttachMany.php b/src/AttachMany.php index 0a13101..5bb164a 100644 --- a/src/AttachMany.php +++ b/src/AttachMany.php @@ -39,7 +39,7 @@ class AttachMany extends Field public $component = 'nova-attach-many'; - public function __construct($name, $attribute = null, $resource = null) + public function __construct($name, $attribute = null, $resource = null, $pivot = null) { parent::__construct($name, $attribute); @@ -51,9 +51,9 @@ public function __construct($name, $attribute = null, $resource = null) $this->resourceName = $resource::uriKey(); $this->manyToManyRelationship = $this->attribute; - $this->fillUsing(function($request, $model, $attribute, $requestAttribute) use($resource) { + $this->fillUsing(function($request, $model, $attribute, $requestAttribute) use($resource, $pivot) { if(is_subclass_of($model, 'Illuminate\Database\Eloquent\Model')) { - $model::saved(function($model) use($attribute, $request) { + $model::saved(function($model) use($attribute, $request, $pivot) { // fetch the submitted values $values = json_decode(request()->input($attribute), true); @@ -67,7 +67,12 @@ public function __construct($name, $attribute = null, $resource = null) $filtered_values = array_filter($values); // sync - $changes = $model->$attribute()->sync($filtered_values); + if($pivot) { + $changes = $model->$attribute()->syncWithPivotValues($filtered_values, $pivot); + } else { + $changes = $model->$attribute()->sync($filtered_values); + } + $method = Str::camel($attribute) . 'Synced';