F
Filament13mo ago
Avriant

Custom page many-to-many sync() method creates duplicates (is this really the right way to do it?)

Filament/Laravel Newbie. I want: To store M:M relationship "company_prefecture" in MySQL DB through a pivot Custom Page. I have: A messy code that I want to improve and adjust it to Filament Custom Page conventions.
1) It duplicates entries 2) It does not generate timestamps even though I have those specified in migration I tried: 1. Raw SQL queries (worked) 2. save()/new CompanyPrefecturesModel/fill() approach (couldn't store company_id/prefecture_id, but did manage to generate timestamps this way) 3. sync() (managed to generate entries in my pivot table, but have issues described above) Code:
public function save(): void {

$tenant = Filament::getTenant();
$data = $this->form->getState();

foreach ($data['prefecture_id'] as $prefecture_id) {
$mergedData[] = [
'company_id' => $tenant->id,
'prefecture_id' => $prefecture_id,
];
}
$data = $mergedData;

$companyID = $tenant->id;

$company = auth()->user()->companies->find($companyID);
$Entry = $company->prefectures();

if ($company->pivot->prefecture_ja === null) {

$Entry->sync($data);

Notification::make()
->success()
// ->title(__('filament-panels::resources/pages/edit-record.notifications'))
->title('Entry Created')
->send();
} else {
$Entry->sync($data);

Notification::make()
->success()
// ->title(__('filament-panels::resources/pages/edit-record.notifications'))
->title('Entry Updated')
->send();
}
}
public function save(): void {

$tenant = Filament::getTenant();
$data = $this->form->getState();

foreach ($data['prefecture_id'] as $prefecture_id) {
$mergedData[] = [
'company_id' => $tenant->id,
'prefecture_id' => $prefecture_id,
];
}
$data = $mergedData;

$companyID = $tenant->id;

$company = auth()->user()->companies->find($companyID);
$Entry = $company->prefectures();

if ($company->pivot->prefecture_ja === null) {

$Entry->sync($data);

Notification::make()
->success()
// ->title(__('filament-panels::resources/pages/edit-record.notifications'))
->title('Entry Created')
->send();
} else {
$Entry->sync($data);

Notification::make()
->success()
// ->title(__('filament-panels::resources/pages/edit-record.notifications'))
->title('Entry Updated')
->send();
}
}
Believe it or not, I've spent a month of my post-work time trying to make it work...
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server