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

dannydehaan's avatar

Relationships in Filament repeater

Hi,

I'm currently working on a form with the Filament form builder. It's an awesome package, but i cannot make a BelongsToMany relationship work. When i fill my account_contract table with values, the repeater sees the records and show them, when i try to add, i get the following error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'account_id' in 'field list'

update accounts set account_id = 3, accounts.updated_at = 2023-05-03 16:58:42 where id = 1

I really don't know why filament tries to add a record to my accounts table.

I have 3 models, AccountContract is being used for casting my pivot field:

<?php

use App\Models\Model;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Contracts\HasForms;
use Livewire\Component;

class Account extends Model
{
    public function contracts()
    {
        return $this->belongsToMany(Contract::class)->using(AccountContract::class)->withPivot(['meta']);
    }
}

class Contract extends Model
{
    public function accounts()
    {
        return $this->belongsToMany(Account::class)->using(AccountContract::class)->withPivot(['meta']);
    }
}

class AccountContract extends Model
{
    public $timestamps = false;

    protected $casts = [
        'meta' => 'json'
    ];
}

class Form extends Component implements HasForms
{
    use InteractsWithForms;

    public function getFormSchema(): array
    {
        return [
            Repeater::make('accounts')
                ->relationship()
                ->schema([
                    Select::make('account_id')
                        ->label('Account')
                        ->options([
                            1 => 'Name 1',
                            2 => 'Name 2',
                            3 => 'Name 3',
                        ])
                ]),
        ];
    }

    public function getFormModel(): \Illuminate\Database\Eloquent\Model|string|null
    {
        return Contract::class;
    }

    public function submit()
    {
        $contract = Contract::query()
            ->create($this->form->getState());

        $this->form->model($contract)->saveRelationships();
    }
}

Does someone know the solution, if yes, i like to hear from you.

0 likes
3 replies
kokoshneta's avatar

@hasanhatem @tabatii The belongsToMany() method returns a query builder on the relationship table, not the pivot table. You should be using Select::make('id') instead, since that is the name of the property in your Account model. You have an account_id property in your pivot model, but that will be automatically calculated by Filament/Laravel when inserting or updating the record.

Please or to participate in this conversation.