Laravel-Backpack / medialibrary-uploaders

MIT License
10 stars 4 forks source link

Pass $entry to `whenSaving` Closure #33

Open karandatwani92 opened 4 months ago

karandatwani92 commented 4 months ago

A user requested this feature so Devs can use $entry inside whenSaving closure to name files more logically.

For example, $entry->slug as file name:

CRUD::field('main_image')
->label('Main Image')
->type('image')
->withMedia([
  'whenSaving' => function($spatieMedia, $backpackMediaObject, $entry) {
    return $spatieMedia->usingFileName($entry->slug.'.jpg')->withResponsiveImages();
  }
]);

But one problem here: I'm unable to figure out $index if used in subfield:

CRUD::field('gallery')
    ->type('repeatable')
    ->tab('Media')
    ->subfields([
        [
            'name' => 'image_title',
            'type' => 'text',
            'wrapper' => [
                'class' => 'form-group col-md-6',
            ],
        ],
        [
            'name' => 'gallery_image',
            'label' => 'image',
            'type' => 'image',
            'wrapper' => [
                'class' => 'form-group col-md-6',
            ],
            'withMedia' => [
                'whenSaving' => function ($spatieMedia, $backpackMediaObject, $entry) {
                    $index = 0; // <------HERE-----
                    $sub_slug = Str::slug($entry->gallery[$index]["image_title"]);
                    return $spatieMedia->usingFileName($sub_slug . '.jpg')->withResponsiveImages();
                }
            ],
        ]
    ]);