I have two models Student and StudentFeePayment. They have one-to-one relationship as below:
// In Student model
public function studentFeePayment()
{
return $this->hanOne(StudentFeePayment::class);
}
//In StudentFeePayment model
public function student() {
return $this->belongsTo(Student::class);
}
In the filament StudentResource file, I am trying to implement custom saving logic of the relationship studentFeePayment.
Fieldset::make('Payment')
->relationship('studentFeePayment')
->schema([ ...... ])
First I tried to implement inside getHeaderActions() inside ListStudent file but relationship items are not available, data only for the resource model(Student) are available. Is this a normal behaviour?
class ListStudents extends ListRecords
{
protected static string $resource = StudentResource::class;
protected function getHeaderActions(): array
{
return [
ActionsCreateAction::make()->label('Register New Student')
->using(function (array $data, string $model): Model {
// Here $data does not contain relationship items
})
];
}
}
Next from this link I tried to implement using saveRelationshipsUsing()
Fieldset::make('Payment')
->relationship('studentFeePayment')
->schema([ .... ])
->saveRelationshipsUsing(function (Model $student, $state){
StudentService::createStudentFeePayment($student, $state);
})
It works only for Create action if I set false
to relationship()
second parameter as below:
Fieldset::make('Payment')
->relationship('studentFeePayment', false)
->schema([ .... ])
->saveRelationshipsUsing(function (Model $student, $state){
StudentService::createStudentFeePayment($student, $state);
})
For Edit/ Update action it does not works as it tried to delete the existing StudentFeePayment record. However, it works, if I remove the false
setting in the relationship()
2nd paramenter.
So it seems like I have to set false
and true
for Create and Update actions respectively.
So I want to know a consistent way to implement custom saving of relationship data in Laravel Filament.
Note: I use action modals for create and edit actions.