Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Norbertho's avatar

How to use after function?

I would like to save product images in a separate table in the database. I know i have to use the

->after(function () {
    // Runs after the form fields are saved to the database.
})

But where to chain this function exactly? In the ProductResurce.php?

0 likes
6 replies
tisuchi's avatar

@norbertho Probably you can try this:


Forms\Components\FileUpload::make('images')
                    ->multiple() // Allow multiple file uploads
                    ->label('Product Images')
                    ->after(function ($state, $model) {
                        // Save the images after the product is saved
                        if ($state) {
                            foreach ($state as $image) {
                                $model->images()->create([
                                    'path' => $image, // Path to the uploaded image
                                ]);
                            }
                        }
                    }),
Norbertho's avatar

@tisuchi Hi unfortunatelly it is not the solution. I have the relationship on the model but it doesn't seams wokring. $model is empty it seams like doesnt get the saved product muodel..

Rebwar's avatar
Rebwar
Best Answer
Level 32

@norbertho you can use saveRelationshipsUsing() method to store images in the related table.

FileUpload::make('images')
    ->multiple()
    ->label('Product images')
    ->saveRelationshipsUsing(function ($state, $record) {
        foreach ($state as $imagePath) {
            $record->images()->create([
                'path' => $imagePath,
            ]);
        }
    }),
1 like
Norbertho's avatar

@Rebwar Thanks it works. However would be good to know why the after() method dont works. But thanks I was researching all affternoon, finally i can keep going..

Rebwar's avatar

@Norbertho The after()method can be used with the CreateAction to perform custom actions after a record is created. Alternatively, you can use the afterCreate hook in CreateProduct.php to handle any post-save actions, such as saving related product images or processing additional data associated with the saved record.

// CreateProduct.php

protected function afterCreate(): void
{
    // Retrieve uploaded images from the form state
    $uploadedImages = $this->form->getState()['images'];

    // Save each uploaded image as a related record
    foreach ($uploadedImages as $imagePath) {
        $this->record->images()->create([
            'path' => $imagePath,
        ]);
    }
}

You can find more hooks in the documentation.

1 like

Please or to participate in this conversation.