Laravel Filament 3 RichEditor fileAttachnetsDirectory - save files in different directory for every model

188 views Asked by At

I have Post model with main_text column which I edit using RichEditor so I can add some photos between the text. This works all good and fine except that when I delete the post all the photos are not being deleted with the post which is bad. I came up with an idea to store the photos in separate directory different for every post. This way I can delete the directory when the post is deleted.

This is what I came up with:

class PostResource extends Resource
{
  $attachmentDirectory = uniqid();

  return $form
     ->schema([
         Forms\Componenta\Hidden::make('attachments_directory')
            ->default($attachmentDirectory),
         RichEditor::make('main_text')
            ->fileAttachmentsDirectory(function() use ($attachmentDirectory) {
               return 'public/posts/' . $attachmentDirectory;
            }),
     ]);

...

This works fine when I create a new record but not so good when the existing record is edited because the attachmentDirectory in generated again which is wrong because while editing it should be taken from existing already record.

So my question is:

how in PostResource can I access the existing record (if the record is edited) and take the data of attachment_directory and pass it to the RichEditor so it can know where to store the files?

1

There are 1 answers

0
Kornel On

I just find the answer. The value of attachments_directory column in existing record can be accessed like so:

$form->model->attachments_directory

so I can do this:

public static function form(Form $form): Form
{
   $attachmentDirectory = $form->model->attachments_directory ?? uniqid();

        return $form
            ->schema([
...