【问题标题】:Laravel Nova required image upload on every editLaravel Nova 每次编辑都需要上传图片
【发布时间】:2019-07-04 13:21:48
【问题描述】:

我正在使用laravel-nova,在一个资源上我正在使用Image 字段:

use Laravel\Nova\Fields\Image;

Image::make('Top Image', 'hero_image')
      ->help('Upload an image to display as hero')
      ->disk('local')
      ->maxWidth(400)
      ->prunable()
      ->rules('required')
      ->hideFromIndex(),

到目前为止一切都很好,但由于它是必需的,所以每次我想编辑资源时都必须上传(相同的)图像,这有点烦人,我不想让它不需要。

那么,有解决办法吗?

【问题讨论】:

  • 要么将上传的图像发送到您的前端,以便每次都再次上传(并处理和保存,这可能不是您想要的),或者不将其设置为我猜需要?

标签: php laravel laravel-nova


【解决方案1】:

首先,你想让它只在创建时需要,所以你应该使用->creationRules('required')而不是->rules('required')

但问题是用户可以删除照片,并在没有图像的情况下保存资源。

要解决此问题,您只需使用 ->deletable(false) 禁用字段上的删除功能。

Image::make('Top Image', 'hero_image')
    ->help('Upload an image to display as hero')
    ->disk('local')
    ->maxWidth(400)
    ->prunable()
    ->creationRules('required')
    ->deletable(false)
    ->hideFromIndex(),

这将使您无需每次都上传图片即可更新资源。并且用户只能用另一个图像替换原始图像。

【讨论】:

  • 谢谢,这对我有用 :-) 我不知道 creationRules('required) 的方法 - 在文档中吗?无论如何,再次感谢!
  • @ST80 没问题!是的,creationRules 应该在文档中:)
【解决方案2】:

我是这样整理的,我先试试看我是否已经把图片保存在我的模型上,然后确定我是否需要它。

$imageRules =  $this->company_logo ? 'sometimes' : 'required';
    return [
        Image::make('Shop Logo', 'company_logo')
            ->disk('images')
           ->rules($imageRules, 'mimes:png')
            ->disableDownload()->deletable(false),

我希望这可以帮助其他人。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-16
    • 1970-01-01
    • 2020-11-30
    • 1970-01-01
    • 2014-10-31
    相关资源
    最近更新 更多