import with belongstomany fields

I have the following fields that the user has to add for the csv upload: - first_name - last_name - email - role - company name I want to updateOrCreate name and email in the users table while I want to attach role and company to the newly created / existing user. I am trying to achieve this with the following:
public function resolveRecord(): ?User
{
$this->extraData = [
'company_name' => $this->data['company_name'],
'role' => $this->data['role'],
];

unset($this->data['company_name']);
unset($this->data['role']);

return User::firstOrNew(
['email' => $this->data['email']],
[
'first_name' => $this->data['first_name'],
'last_name' => $this->data['last_name'],
'email' => $this->data['email']
]
);
}
public function resolveRecord(): ?User
{
$this->extraData = [
'company_name' => $this->data['company_name'],
'role' => $this->data['role'],
];

unset($this->data['company_name']);
unset($this->data['role']);

return User::firstOrNew(
['email' => $this->data['email']],
[
'first_name' => $this->data['first_name'],
'last_name' => $this->data['last_name'],
'email' => $this->data['email']
]
);
}
protected function afterSave(): void
{
$userService = new UserService();
$user = $userService->getUserByEmailId($this->data['email']);

$user->assignRole($this->extraData['role']);
$companyService = new CompanyService();
$company = $companyService->getCompanyByName($this->extraData['company_name']);

$user->companies()->attach($company->id);
}
protected function afterSave(): void
{
$userService = new UserService();
$user = $userService->getUserByEmailId($this->data['email']);

$user->assignRole($this->extraData['role']);
$companyService = new CompanyService();
$company = $companyService->getCompanyByName($this->extraData['company_name']);

$user->companies()->attach($company->id);
}
But the user is not persisting and hence the afterSave is also not working. So all in all, both resolverecord and aftersave, both are not working. What am I doing wrong?
0 Replies
No replies yetBe the first to reply to this messageJoin