Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

asegumpan's avatar

Laravel Livewire - Data not saved in the database

I'm new to livewire and currently I created a simple crud that can save the student data. My database schema are student table, families table and family_student table.

Student TAble

Schema::create('students', function (Blueprint $table) { $table->id(); $table->string('last_name'); $table->string('middle_name'); $table->string('first_name'); $table->date('dob'); $table->timestamps(); });

Families Table

Schema::create('families', function (Blueprint $table) { $table->id(); $table->string('f_last_name'); $table->string('f_middle_name'); $table->string('f_first_name'); $table->string('f_occupation'); $table->timestamps(); }); Family Student Table

Schema::create('family_student', function (Blueprint $table) { $table->id(); $table->foreignId('student_id')->constrained(); $table->foreignId('family_id')->constrained(); $table->boolean('isParent')->default(0); $table->boolean('guardianStudentLiving')->default(0); $table->timestamps(); }); In the livewire part I populate 3 sets of input that and all data will be save in the same columns.

LIVEWIRE

public $last_name;
public $middle_name;
public $first_name;
public $dob;
public $f_last_name;
public $f_middle_name;
public $f_first_name;
public $f_occupation;
public $isParent = null;
public $guardianStudentLiving = null;

public $getData;

public $parentCollections = [];
public $setFields = 3;

// Set sang rules for validation
protected $rules = [
    'last_name' => ['required'],
    'middle_name' => ['required'],
    'first_name' => ['required'],
    'dob' => ['required'],
    'f_last_name.*' => ['required'],
    'f_middle_name.*' => ['required'],
    'f_first_name.*' => ['required'],
    'f_occupation.*' => ['required'],
    'guardianStudentLiving.*' => ['required'],
];
// relatime validation trigger sang update function
public function updated($propertyName){
   $this->validateOnly($propertyName);
}

// save data in db
public function store(){
    $studentData = ModelsStudent::create([
        'last_name' => $this->last_name,
        'middle_name' => $this->middle_name,
        'first_name' => $this->first_name,
        'dob' => $this->dob,
    ]);

    $isParent = $this->isParent != null ? 1 : 0;
    $guardianStudentLiving = $this->guardianStudentLiving  != null ? 1 : 0;

    foreach ($this->parentCollections as $key => $parentCollection) {
        $parent = ModelsFamily::create([
            ['f_last_name' => $parentCollection['f_last_name']],
            ['f_middle_name' => $parentCollection['f_middle_name']],
            ['f_first_name' => $parentCollection['f_first_name']],
            ['f_occupation' => $parentCollection['f_occupation']],
        ]);

        foreach ($parentCollection as $key => $value) {
            $value = $this->studentData->families()->attach($key,
            [
                'isParent' => $isParent,
                'guardianStudentLiving' => $guardianStudentLiving,
                'created_at' => now(),
                'updated_at' => now()
            ]);
        }
    }

    session()->flash('message','The data successfully saved!');

    $this->reset();
}

public function mount(){
     //get data
    $this->getData = ModelsStudent::with(['families:id,f_last_name,f_middle_name,f_first_name,f_occupation'])->select('id','first_name','middle_name','last_name')->get();

    //creating 3 sets of input fields
    for ($i=0; $i < $this->setFields; $i++) {
        $this->parentCollections[] = [
            'f_last_name' => '',
            'f_middle_name' => '',
            'f_first_name' => '',
            'occupation'    => ''
        ];
    }
}

public function render()
{
    return view('livewire.student.student');
}

LIVEWIRE FORM

<form wire:submit.prevent='store'>
    @csrf
    @if (session()->has('message'))
        <div class="px-6 py-4 bg-blue-50 rounded-lg text-blue-500">
            {{ session('message') }}
        </div>
    @endif
    <div>
        <h5 class="text-lg mb-5">Student Information</h5>
        <div class="flex flex-row space-x-4">
            <x-label>{{ __('last name') }}</x-label>
            <x-input wire:model.lazy='last_name' name="last_name" id="last_name" type="text" required></x-input>
            <x-label>{{ __('middle name') }}</x-label>
            <x-input wire:model.lazy='middle_name' name="middle_name" id="middle_name" type="text" required></x-input>
            <x-label>{{ __('first name') }}</x-label>
            <x-input wire:model.lazy='first_name' name="first_name" id="first_name" type="text" required></x-input>
            <x-label>{{ __('date of birth') }}</x-label>
            <x-input type="date" wire:model.lazy='dob'  name="dob" id="dob" required></x-input>
        </div>
        <hr class="my-12">
        <h5 class="text-lg mb-5">Parent Information</h5>

        {{-- @for ($i = 0 ; $i < 3 ; $i++)
            <div class="flex flex-row mb-8">{{ ($i === 1) ? 'Father' : (($i === 2) ? 'Mother' : 'Guardian') }} {{ __("'s Info") }}</div>
            <livewire:student.parent-input :i="$i" :wire:key='$i'>
        @endfor --}}

            @foreach ($parentCollections as $key => $parentCollection)
                <div class="flex flex-row mb-6">
                    <x-label class="text-bold">
                        {{ ($key === 0) ? 'Father' : (($key === 1) ? 'Mother' : 'Guardian') }} {{ __("'s Info") }} <span class="text-red-500 text-bold text-lg">*</span>
                    </x-label>
                </div>
                <div>
                    <div class="grid grid-cols-4 grid-rows-1 grid-flow-row gap-4">
                       <div>
                            <div class="flex flex-col">
                                <x-label class="text-xs">{{ __('LAST NAME') }}</x-label>
                                <x-input wire:key='parentCollections[{{ $key }}][ f_last_name ]' wire:model.lazy='parentCollections.{{ $key }}.f_last_name' class="mb-8" placeholder="Last name"/>
                                @error('parentCollections.{{ $key }}.f_last_name') <span class="text-red-500 error">{{ $message }}</span>@enderror
                            </div>
                       </div>
                       <div>
                            <div class="flex flex-col">
                                <x-label class="text-xs">{{ __('MIDDLE NAME') }}</x-label>
                                <x-input wire:key='parentCollections[{{ $key }}][ f_middle_name ]' wire:model.lazy='parentCollections.{{ $key }}.f_middle_name' class="mb-8"/>
                                @error('f_middle_name.{{ $parentCollections }}') <span class="text-red-500 error">{{ $message }}</span>@enderror
                            </div>
                       </div>
                       <div>
                            <div class="flex flex-col">
                                <x-label class="text-xs">{{ __('FIRST NAME') }}</x-label>
                                <x-input wire:key='parentCollections[{{ $key }}][ f_first_name ]' wire:model.lazy='parentCollections.{{ $key }}.f_first_name' class="mb-8"/>
                            </div>
                       </div>
                        <div>
                            <div class="flex flex-col">
                                <x-label class="text-xs">{{ __('OCCUPATION') }}</x-label>
                                <x-input wire:key='parentCollections[{{ $key }}][ f_occupation ]' wire:model.lazy='parentCollections.{{ $key }}.f_occupation' class="mb-8"/>
                            </div>
                        </div>
                    </div>
                    @if ($key > 1)
                        <div class="flex flex-row space-x-4 content-center">
                            <x-checkbox wire:key='guardianStudentLiving.{{ $key }}' wire:model.lazy='guardianStudentLiving.{{ $key }}' name="guardianStudentLiving.{{ $key }}" class="mb-8"/>
                            <x-label class="text-md">{{ __('Is guardian living with the student?') }}</x-label>
                        </div>
                    @endif
                </div>
            @endforeach

        <x-button wire:submit.prevent='store' type="submit" class="mt-8">{{ __("Submit") }}</x-button>

    </div>
</form>

Now my problem is, every time I save the data the only data will be save are the student data only and it dispalyed an error like this.

enter image description here

How can I save the multiple input data in the families table?

I want to save the 3 sets of families data to be save in the database at the same time is attached the pivot column.

0 likes
6 replies
JabatoForever's avatar

Can i see the model have u set the fillable on it, in case u didn't i would suggest in your models

protected $guarded = ['id']

OR even

protected $guarded = []
1 like
asegumpan's avatar

@JabatoForever this is my model STUDENT MODEL class Student extends Model { protected $table = 'students'; use HasFactory;

protected $fillable = [
    'last_name',
    'middle_name',
    'first_name',
    'dob',
];

public function families(){
    return $this->belongsToMany(Family::class)->withPivot(['isParent', 'guardianStudentLiving']);
}

}

FAMILY MODEL class Family extends Model { protected $table = 'families'; use HasFactory;

protected $fillable = [
    'f_last_name',
    'f_middle_name',
    'f_first_name',
    'f_occupation',
];

protected function isParent(): Attribute
{
    return Attribute::make(
        get: fn (string $value) => boolValue($value),
    );
}


public function students(){
    return $this->belongsToMany(Student::class)->withPivot(['isParent', 'guardianStudentLiving']);
}

}

Snapey's avatar

please make sure you format your code blocks with three backticks ``` on their own line before and after your code,

1 like
asegumpan's avatar

I already solved my problem. Thank you for replying my question.

kokoshneta's avatar

@asegumpan You should write up how you solved the problem for any future visitors who see this (there is nothing as frustrating as finally finding someone describing the same problem you’re having, and then at the end it just says, “I solved my problem”, leaving you with no idea what to do). Then you can use the “Set Best Answer” button to mark the thread as solved – that gets it off the “Unsolved” list as well.

1 like
asegumpan's avatar
asegumpan
OP
Best Answer
Level 1

I already solved this problem, in order to solve and save the multiple data in every input fields sets in the 'store ()' instead of

foreach ($this->parentCollections as $key => $parentCollection) {
       $parent = ModelsFamily::create([
           ['f_last_name' => $parentCollection['f_last_name']],
           ['f_middle_name' => $parentCollection['f_middle_name']],
           ['f_first_name' => $parentCollection['f_first_name']],
           ['f_occupation' => $parentCollection['f_occupation']],
       ]);

       foreach ($parentCollection as $key => $value) {
           $value = $this->studentData->families()->attach($key,
           [
               'isParent' => $isParent,
               'guardianStudentLiving' => $guardianStudentLiving,
               'created_at' => now(),
               'updated_at' => now()
           ]);
       }
   }'''

//It must be
//=============================================//

  foreach ($this->parentCollections as $key => $parentCollection) {
					//this the correct  line since I already populate the fields in the mount()
               $parent = ModelsFamily::create($parentCollection);

              $studentData->families()->attach($parent->id,
               [
                   'isParent' => $isParent,
                   'guardianStudentLiving' => $guardianStudentLiving,
                   'created_at' => now(),
                   'updated_at' => now()
               ]);
           }

1 like

Please or to participate in this conversation.