mutateFormDataBeforeCreate not working

I try to use mutateFormDataBeforeCreate to add records according to user input, but it seems this method is not being execute before creating record. I want it to make records as many as the user input the number.
class RoomResource extends Resource
{
protected static ?string $model = Room::class;

protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';

protected static ?string $navigationGroup = 'Room Management';

public static function form(Form $form): Form
{
return $form
->schema([
Select::make('room_type_id')
->required()
->label('Tipe Kamar (ID)')
->options(Room_type::pluck('name_room_id', 'id')->toArray()),
TextInput::make('count')
->label('Jumlah Kamar')
->type('number')
->minValue(1)
->required()
->dehydrated(false)
]);
}

protected function mutateFormDataBeforeCreate(array $data): array
{
dd($data);
if (!isset($data['count']) || !is_numeric($data['count']) || $data['count'] <= 0) {
throw new \InvalidArgumentException('Jumlah kamar harus lebih dari 0.');
}
$count = (int) $data['count'];
$rooms = [];
for ($i = 0; $i < $count; $i++) {
$rooms[] = [
'room_type_id' => $data['room_type_id'],
'status' => 'Available',
'tenant' => null,
'created_at' => now(),
'updated_at' => now(),
];
}
Room::insert($rooms);
return [];
}
class RoomResource extends Resource
{
protected static ?string $model = Room::class;

protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';

protected static ?string $navigationGroup = 'Room Management';

public static function form(Form $form): Form
{
return $form
->schema([
Select::make('room_type_id')
->required()
->label('Tipe Kamar (ID)')
->options(Room_type::pluck('name_room_id', 'id')->toArray()),
TextInput::make('count')
->label('Jumlah Kamar')
->type('number')
->minValue(1)
->required()
->dehydrated(false)
]);
}

protected function mutateFormDataBeforeCreate(array $data): array
{
dd($data);
if (!isset($data['count']) || !is_numeric($data['count']) || $data['count'] <= 0) {
throw new \InvalidArgumentException('Jumlah kamar harus lebih dari 0.');
}
$count = (int) $data['count'];
$rooms = [];
for ($i = 0; $i < $count; $i++) {
$rooms[] = [
'room_type_id' => $data['room_type_id'],
'status' => 'Available',
'tenant' => null,
'created_at' => now(),
'updated_at' => now(),
];
}
Room::insert($rooms);
return [];
}
4 Replies
dissto
dissto3w ago
I think you need to add that to your CreateRoom component, not the resource itself 🤔 Customizing data before saving
kiuyha
kiuyhaOP3w ago
So I can't add it to resource? Because I think it more good if it just pop up
toeknee
toeknee3w ago
You do it to the create page within the resource, not the resource
Dennis Koch
Dennis Koch3w ago
Because I think it more good if it just pop up
What do you mean? 🤔

Did you find this page helpful?