F
Filament15mo ago
jlarm

Add Current User to Pivot on save.

I have a Dealership model and the standard User model setup as a belongsToMany with a pivot table. Very basic, but what I am having issues with is when a user creates a new dealership I want to automatically add the user to the pivot table. Prior to having it a belongsToMany it was a hasMany dealerships so I used a boot method on the Dealership model to add the current user_id to the newly created dealership on save, which worked just fine using:
protected static function booted(): void
{
parent::boot();

static::creating(function ($dealership) {
$dealership->user_id = auth()->user()->id;
});
});
protected static function booted(): void
{
parent::boot();

static::creating(function ($dealership) {
$dealership->user_id = auth()->user()->id;
});
});
This is what I currently have for adding user/dealership to the pivot table:
protected static function booted(): void
{
parent::boot();

static::created(function ($dealership) {
$dealership->users()->syncWithoutDetaching(\Auth::id());
});
});
protected static function booted(): void
{
parent::boot();

static::created(function ($dealership) {
$dealership->users()->syncWithoutDetaching(\Auth::id());
});
});
I noticed that if I change from "created" to "saved", then create a new dealership then click the "save changes" button after the dealership has been created it will add the relationship, I just cannot get it to add the relationship on creation. Any help would be appreciated! Thanks
1 Reply
jlarm
jlarmOP15mo ago
Fixed by adding the following to the "CreateDealership" page:
protected function afterCreate(): void
{
$this->record->users()->attach(auth()->user()->id);
}
protected function afterCreate(): void
{
$this->record->users()->attach(auth()->user()->id);
}
Want results from more Discord servers?
Add your server