当前位置: 首页>编程语言>正文

laravel admin hasMany

  • Laravel Version: 8.83
  • PHP Version:8.0
  • Laravel-admin: 1.8.19

问题描述:

$form->hasMany('images', 'images', function (\Encore\Admin\Form\NestedForm $form) {
    $form->multipleImage('images_path', 'images')->removable();
});

在点击删除图片时 删除失败

临时解决方案

namespace App\Admin\Extensions\Form\Field;

use Encore\Admin\Form;

class MultipleImage extends \Encore\Admin\Form\Field\MultipleImage
{

    /**
     * Set default options form image field.
     *
     * @return void
     */
    protected function setupDefaultOptions()
    {
        $defaults = [
            'overwriteInitial' => false,
            'initialPreviewAsData' => true,
            'msgPlaceholder' => trans('admin.choose_file'),
            'browseLabel' => trans('admin.browse'),
            'cancelLabel' => trans('admin.cancel'),
            'showRemove' => false,
            'showUpload' => false,
            'showCancel' => false,
            'dropZoneEnabled' => false,
            'deleteExtraData' => [
                $this->formatName($this->column) => static::FILE_DELETE_FLAG,
                static::FILE_DELETE_FLAG => '',
                '_token' => csrf_token(),
                '_method' => 'PUT',
                '_uu_key' => $this->getErrorKey(), //  重点是这个 key, 可以在http 请求时带上
                // $this->getErrorKey() => images.{id}.images_path
            ],
        ];

        if ($this->form instanceof Form) {
            $defaults['deleteUrl'] = $this->form->resource() . '/' . $this->form->model()->getKey();
        }

        $defaults = array_merge($defaults, ['fileActionSettings' => $this->fileActionSettings]);

        $this->options($defaults);
    }
}

app/Admin/bootstrap.php

\Encore\Admin\Form::forget(['multipleImage']);
\Encore\Admin\Form::extend('multipleImage', App\Admin\Extensions\Form\Field\MultipleImage::class);

你的控制器中

$form->saved(function (Form $form) {
    if (request()->wantsJson() && request()->has(Field::FILE_DELETE_FLAG)) {
        $key = $form->input(\Encore\Admin\Form\Field::FILE_DELETE_FLAG);  // 获取需要删除的键值
        $id = explode('.', $form->input('uu_key'))[1];    // 获取需要删除的数据的id 
        $image = Model::find($id);
        $images = $image->images_path;
        unset($images[$key]);
        $image->images_path = $images;
        $image->save();
        return resonse();
    }
});


https://www.xamrdz.com/lan/5l41994214.html

相关文章: