-
Notifications
You must be signed in to change notification settings - Fork 34
Description
- Laravel Version: 10.x
- Nova Version: 4.23.0
Description:
Same issue as #3639 which was eventually implemented for BelongsToMany.
Say we have a Music model with a contributables pivot which can morph to either Singer or Producer models.
The pivot also has an example field as defined below:
Schema::create('contributables', function (Blueprint $table) {
$table->foreignIdFor(Music::class)->constrained()->cascadeOnDelete();
$table->nullableMorphs('contributable');
$table->string('example');
});app/Models/Music.php
public function singers()
{
return $this->morphedByMany(Singer::class, 'contributables')
->withPivotValue('example', 'some singer value');
}
public function producers()
{
return $this->morphedByMany(Producer::class, 'contributables')
->withPivotValue('example', 'some producer value');
}When I run the below code
$model = Music::find(1);
$model->singers()->attach(Singer::find(1));
$model->producers()->attach(Producer::find(1))New record added to contributables table:
| music_id | contributable_type | contributable_id | example |
|---|---|---|---|
| 1 | singers | 1 | some singer value |
| 1 | producers | 1 | some producer value |
However, when doing this in nova the some singer value and some producer value are not inserted:
app/Nova/MusicResource.php
MorphedByMany::make('Singers', 'singers', SingerResource::class),
MorphedByMany::make('Producers', 'producers', ProducerResource::class),Because example is not nullable it will give the following error when trying to attach:
SQLSTATE[HY000]: General error: 1364 Field 'example' doesn't have a default value (SQL: insert into `contributables` (`music_id`, `contributable_type`, `contributable_id`) values (1, 'singers', 1))Workaround:
Define hidden fields with default values on the field
app/Nova/MusicResource.php
MorphedByMany::make('Singers', 'singers', SingerResource::class)->fields(fn () => [
Hidden::make('example')->default(fn () => 'some singer value')
]),Fix
MorphedResourceAttachController needs to have an equivalent of the Laravel\Nova\Query\Mixin\BelongsToMany::getDefaultPivotAttributes() method that the ResourceAttachController uses to apply the default values.