Attach BelongsToMany after creating a record in from a table

Sorry, the title is weird but I'm not sure how to summarise it. I have a many-to-many relation something like
class Person {
public function rooms() {
return $this->belongsToMany(Room::class);
}
}
class Person {
public function rooms() {
return $this->belongsToMany(Room::class);
}
}
and in the PersonResource table I have the following action
Tables\Actions\CreateAction::make('createRoom')
->button()
->model(Room::class)
->record(null)
->form([
self::getRoomFields(),
]),
Tables\Actions\CreateAction::make('createRoom')
->button()
->model(Room::class)
->record(null)
->form([
self::getRoomFields(),
]),
This works, and a new Room record is created. But I can't find a way to attach this new record to the person we're creating the room for. I can override the action() function and do something like
->action(function (Person $record, array $data) {
$record->rooms()->create($data);
}),
->action(function (Person $record, array $data) {
$record->rooms()->create($data);
}),
but this way I'm losing all the built-in functionality (like the notification, the 'create another' option etc) Is there a way to modify the process so that the default action is executed but I also get access to the created record so that I can at least save the relationship manually? I think I'm missing something obvious here 🤔
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?