Angom
Angom

Reputation: 763

How to save relationship data manually in Laravel Filament V3?

I have two models Student and StudentFeePayment. They have one-to-one relationship as shown here:

// In Student model
public function studentFeePayment()
{
    return $this->hasOne(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 [
            Actions\CreateAction::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){
         // Custom code to save relationship data
         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){
         // Custom code to save relationship data
         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 parameter.

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.

Upvotes: 0

Views: 1081

Answers (1)

Majid M. Alzariey
Majid M. Alzariey

Reputation: 483

If you want to use the FieldSet to only add new records without affecting the current records, you can manipulate the relationship with a where clause that restricts the data from being deleted.

For example, in the Student Model, you can write:


    public function studentFeePayment()
    {
        return $this->hasOne(StudentFeePayment::class)
                   ->where('created_at', '>', now());
    }

Upvotes: 0

Related Questions