How do I add data to two tables in one form submission using filamentphp?

This is the scenario: I have two tables i.e Student and Guardian. They all have one form as stated below The Form

I want when the form is submited. It creates a student gets the student Id and also adds the guardian data along with the student id.

The relationship between the student and guardian is a hasMany Relationship.

Upvotes: 0

Views: 5261

Answers (2)

Go to the resource pages path of the form (app/Filament/Resources/YourResource/Pages/Create***.php)

and follow this code structure

<?php
namespace App\Filament\Resources\StudentResource\Pages;

use App\Filament\Resources\StudentResource;
use Filament\Pages\Actions;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Database\Eloquent\Model;
use App\Models\Guardian;


class CreateStudent extends CreateRecord
{
    protected static string $resource = StudentResource::class;`

    protected function handleRecordCreation(array $data): Model
    {
        //insert the student
        $record =  static::getModel()::create($data);

        // Create a new Guardian model instance
        $guardian = new Guardian();
        $guardian->first_name = $data['guardian_fname'];
        $guardian->last_name = $data['guardian_lname'];
        $guardian->gender = $data['guardian_gender'];
        $guardian->email = $data['guardian_email'];
        $guardian->contact_no = $data['guardian_contact'];

        // Assuming 'student_id' is the foreign key linking to students
        $guardian->student_id = $record->student_id; 

        // Save the Guardian model to insert the data
        $guardian->save();


        return $record;
    }
}

Notice that you have to import the Model of the second table and create an new instance then map each field to the corresponding data, By default all form entries in filament are stored in the $data array.

Upvotes: 3

Ehs4n
Ehs4n

Reputation: 802

This should not be a problem. You can customise the CreateAction in getActions() method by using using() method on Filament\Pages\Actions\CreateAction like this.

protected function getActions(): array
    {
        return [
            Actions\CreateAction::make()
                ->using(function (array $data): Model {
                    $student = static::getModel()->create($studentData);
                    $student->guardian()->create($guardianData);

                    return $student;
                }),
        ];
    }

Upvotes: 0

Related Questions