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
Select::make('companies')
->multiple()
->relationship('companies', 'name')
Select::make('companies')
->multiple()
->relationship('companies', 'name')
?
AngryTestie
AngryTestieOP2y 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
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
AngryTestieOP2y 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
are you using admin panel, resource? Where are you creating the user?
AngryTestie
AngryTestieOP2y ago
Yes I'm creating it in the UserResource
LeandroFerreira
you have a Pages/CreateUser.php class right?
AngryTestie
AngryTestieOP2y ago
yes
Solution
LeandroFerreira
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
AngryTestieOP2y ago
thanks bro

Did you find this page helpful?