Creating a belongsTo Relationship in a Filament Form: Is Fieldset::relationship() the Right Approach
Hello everyone,
I'm working on a personal project to learn Filament and have run into a problem I'd appreciate some help with. I'm trying to create a new Member record, and it has a belongsTo relationship with a Person.
My Goal:
I need to create a new Person and a new Member from a single form. Specifically, when a user fills out the Member creation form, I want to create the associated Person record and then link it to the new Member. I cannot select an existing Person.
My Current Setup:
In my MemberResource, I'm using Fieldset::make('Person')->relationship('person') to handle the Person fields.
The Problem:
This approach works perfectly for editing an existing Member. The person fields are loaded and saved correctly. However, when I try to create a new Member, I get the following error:
SQLSTATE[HY000]: General error: 1364 Field 'person_id' doesn't have a default value
It seems like the Member record is being saved before the Person record is created, causing the person_id column to be null.
My Question:
Is Fieldset::make()->relationship() the correct way to handle the creation of a belongsTo model? Or is there another, more appropriate method for this specific use case?
Any help or guidance would be greatly appreciated. Thank you! π
https://gist.github.com/ShodriLopez/5fdd5ba95440db85d883d45d3e292450
Solution:Jump to solution
That's actually documented right here:
https://filamentphp.com/docs/4.x/forms/overview#saving-data-to-a-belongsto-or-morphto-relationship
I particularly use the Select component with a creation form on it
https://filamentphp.com/docs/4.x/resources/managing-relationships#select--checkbox-list---choose-from-existing-records-or-create-a-new-one...
1 Reply
Solution
That's actually documented right here:
https://filamentphp.com/docs/4.x/forms/overview#saving-data-to-a-belongsto-or-morphto-relationship
I particularly use the Select component with a creation form on it
https://filamentphp.com/docs/4.x/resources/managing-relationships#select--checkbox-list---choose-from-existing-records-or-create-a-new-one