Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add pivot support #104

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
13 changes: 9 additions & 4 deletions src/AttachMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand All @@ -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);
Expand All @@ -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';

Expand Down