How to save morphToMany relationship during create?

Hi, I'm getting the error "Integrity constraint violation: 1048 Column 'categorizable_id' cannot be null" when laravel tries to run
insert into `categorizables` (`categorizable_id`, `categorizable_type`, `category_id`) values (?, App\Models\Content, 3)
insert into `categorizables` (`categorizable_id`, `categorizable_type`, `category_id`) values (?, App\Models\Content, 3)
The model has the following:
public function categories() : MorphToMany
{
return $this->morphToMany(Category::class, 'categorizable');
}
public function categories() : MorphToMany
{
return $this->morphToMany(Category::class, 'categorizable');
}
And the filament resource form has:
Select::make('categories')
->multiple()
->relationship(titleAttribute: 'name')
->createOptionForm([
TextInput::make('name')
->required(),
TextInput::make('description')
->required(),
Select::make('parent_id')
->options(
Category::get()
->pluck('name', 'id')
)
])
->preload()
->visible(function (Get $get) {
return $get('type') === 'post';
})
Select::make('categories')
->multiple()
->relationship(titleAttribute: 'name')
->createOptionForm([
TextInput::make('name')
->required(),
TextInput::make('description')
->required(),
Select::make('parent_id')
->options(
Category::get()
->pluck('name', 'id')
)
])
->preload()
->visible(function (Get $get) {
return $get('type') === 'post';
})
Obviously, the relationship can't be saved till after the parent Content model has been saved, but this seems be trying to do that in the reverse order. Any idea how to get round this? I can't believe I'm the first person to encounter this, so it feels like something I've set up wrong. Andy
Solution:
Hmm. That's really wierd. I've just created a test app with the same models, and it works fine. OK, so something odd about my setup, so I'll look into it further. Appreciate your help, @toeknee...
Jump to solution
5 Replies
toeknee
toeknee7mo ago
categorizable_id isn't being set, it's passed as null. Are you using the createoptionform first?
_andypeacock
_andypeacockOP7mo ago
No, the categories already exist in this case, and I'm tyring to add the relationship at the same time:
toeknee
toeknee7mo ago
This is a standard resource with a standard create page?
_andypeacock
_andypeacockOP7mo ago
Yes
Solution
_andypeacock
_andypeacock7mo ago
Hmm. That's really wierd. I've just created a test app with the same models, and it works fine. OK, so something odd about my setup, so I'll look into it further. Appreciate your help, @toeknee
Want results from more Discord servers?
Add your server