@Snapey
Sorry to disturb you again. So I adjusted the creation logic to this pattern
//model1->relationship()->sync($model2PrimaryIDs)
$company->prefectures()->sync($data)
and removed data mutation (because data coming from the form is jus a bunch of $model2IDs)
foreach ($data['prefecture_id'] as $prefecture_id) {
$mergedData[] = [
'company_id' => $tenant->id,
'prefecture_id' => $prefecture_id,
];
}
$data = $mergedData;
Now my save() looks like this:
public function save(): void {
$tenant = Filament::getTenant();
$data = $this->form->getState(); //dd($data) = array:1 [▼ // app/Filament/Pages/CompanyRegions.php:133 "prefecture_id" => array:3 [▼ 0 => "2" 1 => "4" 2 => "6" ]]
$companyID = $tenant->id;
$company = auth()->user()->companies->find($companyID);
if ($company->prefectures->contains(1) === false) {
$Entry = new ModelsCompanyPrefectures;
$Entry->fill($data); // dd($Entry) = #attributes: array:1 [▼ "prefecture_id" => array:3 [▼ 0 => "3" 1 => "5" 2 => "7" ]]
$Entry->save($data);
//$company->prefectures()->sync($data);
Notification::make()
->success()
->title('Entry Created')
->send();
} else {
// $Entry->update($data);
$company->prefectures()->detach();
$company->prefectures()->sync($data);
Notification::make()
->success()
->title('Entry Updated')
->send();
}
}
I'm supposed to be passing the array of $model2_ids (prefectures), which is what I think I'm doing, yet without data mutation it throws errors depending on what I do. Should I be doing data mutation regardless?
For instance, if I do $company->prefectures()->sync($data) or $Entry = new ModelsCompanyPrefectures; $Entry->fill($data); it removes timestamps created by Eloquent and associates array keys with table columns, which results in the following error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'field list'
insert into
`company_prefectures` (`company_id`, `0`, `1`, `2`)
values
(1, 2, 4, 6)
Doing $Entry->save($data) or $Entry->save(array_values($data)) will generate timestamps, but throw this error
ksort(): Argument #1 ($array) must be of type array, string given
What is it that I'm lacking to figure this out? Even if I hypothetically bring back the data mutation, timestamp issue would persist. Sorry if this is very basic, but at least I think I did my share of web search before posting my issue.
I honestly feel lost :( I just can't help but feel like all this process is probably already figured out for me and I just don't know the piece required to follow the path laid out for me by the Laravel/Filament devs.
UPD: People suggest using pivot model architecture as one possible solution (Github), maybe I should try it with my Custom Page