Insert Data in Pivot Table

I have 2 tables companies and users with many to many relationship, now I want to add data in pivot table when I'm creating new user how can I do that?Please help
Solution:
```php protected function afterCreate(): void { //companies that you want to attach $companies = [1,2,3..];...
Jump to solution
10 Replies
LeandroFerreira
LeandroFerreira17mo ago
Select::make('companies')
->multiple()
->relationship('companies', 'name')
Select::make('companies')
->multiple()
->relationship('companies', 'name')
?
AngryTestie
AngryTestieOP17mo ago
What if I don't have the select form when creating a new user. I customize the filament breezy registration and added a company field that's why the user logged in belongs to a company already,.
LeandroFerreira
LeandroFerreira17mo ago
you can use a hook as afterCreate to sync companies I think https://filamentphp.com/docs/2.x/admin/resources/creating-records#lifecycle-hooks
Filament
Creating records - Resources - Admin Panel - Filament
The elegant TALL stack admin panel for Laravel artisans.
AngryTestie
AngryTestieOP17mo ago
can you give me an example on how to do this sorry I'm new. how can I access the id of the created user so I can attach or sync it with the related table
LeandroFerreira
LeandroFerreira17mo ago
are you using admin panel, resource? Where are you creating the user?
AngryTestie
AngryTestieOP17mo ago
Yes I'm creating it in the UserResource
LeandroFerreira
LeandroFerreira17mo ago
you have a Pages/CreateUser.php class right?
AngryTestie
AngryTestieOP17mo ago
yes
Solution
LeandroFerreira
LeandroFerreira17mo ago
protected function afterCreate(): void
{
//companies that you want to attach
$companies = [1,2,3..];

//use sync or attach to attach the companies
$this->record->companies()->sync($companies);
}
protected function afterCreate(): void
{
//companies that you want to attach
$companies = [1,2,3..];

//use sync or attach to attach the companies
$this->record->companies()->sync($companies);
}
AngryTestie
AngryTestieOP17mo ago
thanks bro
Want results from more Discord servers?
Add your server